File: | tools/clang/lib/CodeGen/CodeGenModule.cpp |
Warning: | line 685, column 20 Called C++ object pointer is null |
[?] Use j/k keys for keyboard navigation
1 | //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// | |||
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 coordinates the per-module state used while generating code. | |||
11 | // | |||
12 | //===----------------------------------------------------------------------===// | |||
13 | ||||
14 | #include "CodeGenModule.h" | |||
15 | #include "CGBlocks.h" | |||
16 | #include "CGCUDARuntime.h" | |||
17 | #include "CGCXXABI.h" | |||
18 | #include "CGCall.h" | |||
19 | #include "CGDebugInfo.h" | |||
20 | #include "CGObjCRuntime.h" | |||
21 | #include "CGOpenCLRuntime.h" | |||
22 | #include "CGOpenMPRuntime.h" | |||
23 | #include "CGOpenMPRuntimeNVPTX.h" | |||
24 | #include "CodeGenFunction.h" | |||
25 | #include "CodeGenPGO.h" | |||
26 | #include "ConstantEmitter.h" | |||
27 | #include "CoverageMappingGen.h" | |||
28 | #include "TargetInfo.h" | |||
29 | #include "clang/AST/ASTContext.h" | |||
30 | #include "clang/AST/CharUnits.h" | |||
31 | #include "clang/AST/DeclCXX.h" | |||
32 | #include "clang/AST/DeclObjC.h" | |||
33 | #include "clang/AST/DeclTemplate.h" | |||
34 | #include "clang/AST/Mangle.h" | |||
35 | #include "clang/AST/RecordLayout.h" | |||
36 | #include "clang/AST/RecursiveASTVisitor.h" | |||
37 | #include "clang/Basic/Builtins.h" | |||
38 | #include "clang/Basic/CharInfo.h" | |||
39 | #include "clang/Basic/Diagnostic.h" | |||
40 | #include "clang/Basic/Module.h" | |||
41 | #include "clang/Basic/SourceManager.h" | |||
42 | #include "clang/Basic/TargetInfo.h" | |||
43 | #include "clang/Basic/Version.h" | |||
44 | #include "clang/CodeGen/ConstantInitBuilder.h" | |||
45 | #include "clang/Frontend/CodeGenOptions.h" | |||
46 | #include "clang/Sema/SemaDiagnostic.h" | |||
47 | #include "llvm/ADT/Triple.h" | |||
48 | #include "llvm/Analysis/TargetLibraryInfo.h" | |||
49 | #include "llvm/IR/CallSite.h" | |||
50 | #include "llvm/IR/CallingConv.h" | |||
51 | #include "llvm/IR/DataLayout.h" | |||
52 | #include "llvm/IR/Intrinsics.h" | |||
53 | #include "llvm/IR/LLVMContext.h" | |||
54 | #include "llvm/IR/Module.h" | |||
55 | #include "llvm/ProfileData/InstrProfReader.h" | |||
56 | #include "llvm/Support/ConvertUTF.h" | |||
57 | #include "llvm/Support/ErrorHandling.h" | |||
58 | #include "llvm/Support/MD5.h" | |||
59 | ||||
60 | using namespace clang; | |||
61 | using namespace CodeGen; | |||
62 | ||||
63 | static llvm::cl::opt<bool> LimitedCoverage( | |||
64 | "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden, | |||
65 | llvm::cl::desc("Emit limited coverage mapping information (experimental)"), | |||
66 | llvm::cl::init(false)); | |||
67 | ||||
68 | static const char AnnotationSection[] = "llvm.metadata"; | |||
69 | ||||
70 | static CGCXXABI *createCXXABI(CodeGenModule &CGM) { | |||
71 | switch (CGM.getTarget().getCXXABI().getKind()) { | |||
72 | case TargetCXXABI::GenericAArch64: | |||
73 | case TargetCXXABI::GenericARM: | |||
74 | case TargetCXXABI::iOS: | |||
75 | case TargetCXXABI::iOS64: | |||
76 | case TargetCXXABI::WatchOS: | |||
77 | case TargetCXXABI::GenericMIPS: | |||
78 | case TargetCXXABI::GenericItanium: | |||
79 | case TargetCXXABI::WebAssembly: | |||
80 | return CreateItaniumCXXABI(CGM); | |||
81 | case TargetCXXABI::Microsoft: | |||
82 | return CreateMicrosoftCXXABI(CGM); | |||
83 | } | |||
84 | ||||
85 | llvm_unreachable("invalid C++ ABI kind")::llvm::llvm_unreachable_internal("invalid C++ ABI kind", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 85); | |||
86 | } | |||
87 | ||||
88 | CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO, | |||
89 | const PreprocessorOptions &PPO, | |||
90 | const CodeGenOptions &CGO, llvm::Module &M, | |||
91 | DiagnosticsEngine &diags, | |||
92 | CoverageSourceInfo *CoverageInfo) | |||
93 | : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO), | |||
94 | PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags), | |||
95 | Target(C.getTargetInfo()), ABI(createCXXABI(*this)), | |||
96 | VMContext(M.getContext()), Types(*this), VTables(*this), | |||
97 | SanitizerMD(new SanitizerMetadata(*this)) { | |||
98 | ||||
99 | // Initialize the type cache. | |||
100 | llvm::LLVMContext &LLVMContext = M.getContext(); | |||
101 | VoidTy = llvm::Type::getVoidTy(LLVMContext); | |||
102 | Int8Ty = llvm::Type::getInt8Ty(LLVMContext); | |||
103 | Int16Ty = llvm::Type::getInt16Ty(LLVMContext); | |||
104 | Int32Ty = llvm::Type::getInt32Ty(LLVMContext); | |||
105 | Int64Ty = llvm::Type::getInt64Ty(LLVMContext); | |||
106 | HalfTy = llvm::Type::getHalfTy(LLVMContext); | |||
107 | FloatTy = llvm::Type::getFloatTy(LLVMContext); | |||
108 | DoubleTy = llvm::Type::getDoubleTy(LLVMContext); | |||
109 | PointerWidthInBits = C.getTargetInfo().getPointerWidth(0); | |||
110 | PointerAlignInBytes = | |||
111 | C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity(); | |||
112 | SizeSizeInBytes = | |||
113 | C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity(); | |||
114 | IntAlignInBytes = | |||
115 | C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity(); | |||
116 | IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); | |||
117 | IntPtrTy = llvm::IntegerType::get(LLVMContext, | |||
118 | C.getTargetInfo().getMaxPointerWidth()); | |||
119 | Int8PtrTy = Int8Ty->getPointerTo(0); | |||
120 | Int8PtrPtrTy = Int8PtrTy->getPointerTo(0); | |||
121 | AllocaInt8PtrTy = Int8Ty->getPointerTo( | |||
122 | M.getDataLayout().getAllocaAddrSpace()); | |||
123 | ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace(); | |||
124 | ||||
125 | RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); | |||
126 | BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC(); | |||
127 | ||||
128 | if (LangOpts.ObjC1) | |||
129 | createObjCRuntime(); | |||
130 | if (LangOpts.OpenCL) | |||
131 | createOpenCLRuntime(); | |||
132 | if (LangOpts.OpenMP) | |||
133 | createOpenMPRuntime(); | |||
134 | if (LangOpts.CUDA) | |||
135 | createCUDARuntime(); | |||
136 | ||||
137 | // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. | |||
138 | if (LangOpts.Sanitize.has(SanitizerKind::Thread) || | |||
139 | (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) | |||
140 | TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(), | |||
141 | getCXXABI().getMangleContext())); | |||
142 | ||||
143 | // If debug info or coverage generation is enabled, create the CGDebugInfo | |||
144 | // object. | |||
145 | if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo || | |||
146 | CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes) | |||
147 | DebugInfo.reset(new CGDebugInfo(*this)); | |||
148 | ||||
149 | Block.GlobalUniqueCount = 0; | |||
150 | ||||
151 | if (C.getLangOpts().ObjC1) | |||
152 | ObjCData.reset(new ObjCEntrypoints()); | |||
153 | ||||
154 | if (CodeGenOpts.hasProfileClangUse()) { | |||
155 | auto ReaderOrErr = llvm::IndexedInstrProfReader::create( | |||
156 | CodeGenOpts.ProfileInstrumentUsePath); | |||
157 | if (auto E = ReaderOrErr.takeError()) { | |||
158 | unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, | |||
159 | "Could not read profile %0: %1"); | |||
160 | llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) { | |||
161 | getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath | |||
162 | << EI.message(); | |||
163 | }); | |||
164 | } else | |||
165 | PGOReader = std::move(ReaderOrErr.get()); | |||
166 | } | |||
167 | ||||
168 | // If coverage mapping generation is enabled, create the | |||
169 | // CoverageMappingModuleGen object. | |||
170 | if (CodeGenOpts.CoverageMapping) | |||
171 | CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo)); | |||
172 | } | |||
173 | ||||
174 | CodeGenModule::~CodeGenModule() {} | |||
175 | ||||
176 | void CodeGenModule::createObjCRuntime() { | |||
177 | // This is just isGNUFamily(), but we want to force implementors of | |||
178 | // new ABIs to decide how best to do this. | |||
179 | switch (LangOpts.ObjCRuntime.getKind()) { | |||
180 | case ObjCRuntime::GNUstep: | |||
181 | case ObjCRuntime::GCC: | |||
182 | case ObjCRuntime::ObjFW: | |||
183 | ObjCRuntime.reset(CreateGNUObjCRuntime(*this)); | |||
184 | return; | |||
185 | ||||
186 | case ObjCRuntime::FragileMacOSX: | |||
187 | case ObjCRuntime::MacOSX: | |||
188 | case ObjCRuntime::iOS: | |||
189 | case ObjCRuntime::WatchOS: | |||
190 | ObjCRuntime.reset(CreateMacObjCRuntime(*this)); | |||
191 | return; | |||
192 | } | |||
193 | llvm_unreachable("bad runtime kind")::llvm::llvm_unreachable_internal("bad runtime kind", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 193); | |||
194 | } | |||
195 | ||||
196 | void CodeGenModule::createOpenCLRuntime() { | |||
197 | OpenCLRuntime.reset(new CGOpenCLRuntime(*this)); | |||
198 | } | |||
199 | ||||
200 | void CodeGenModule::createOpenMPRuntime() { | |||
201 | // Select a specialized code generation class based on the target, if any. | |||
202 | // If it does not exist use the default implementation. | |||
203 | switch (getTriple().getArch()) { | |||
204 | case llvm::Triple::nvptx: | |||
205 | case llvm::Triple::nvptx64: | |||
206 | assert(getLangOpts().OpenMPIsDevice &&(static_cast <bool> (getLangOpts().OpenMPIsDevice && "OpenMP NVPTX is only prepared to deal with device code.") ? void (0) : __assert_fail ("getLangOpts().OpenMPIsDevice && \"OpenMP NVPTX is only prepared to deal with device code.\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 207, __extension__ __PRETTY_FUNCTION__)) | |||
207 | "OpenMP NVPTX is only prepared to deal with device code.")(static_cast <bool> (getLangOpts().OpenMPIsDevice && "OpenMP NVPTX is only prepared to deal with device code.") ? void (0) : __assert_fail ("getLangOpts().OpenMPIsDevice && \"OpenMP NVPTX is only prepared to deal with device code.\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 207, __extension__ __PRETTY_FUNCTION__)); | |||
208 | OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this)); | |||
209 | break; | |||
210 | default: | |||
211 | if (LangOpts.OpenMPSimd) | |||
212 | OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this)); | |||
213 | else | |||
214 | OpenMPRuntime.reset(new CGOpenMPRuntime(*this)); | |||
215 | break; | |||
216 | } | |||
217 | } | |||
218 | ||||
219 | void CodeGenModule::createCUDARuntime() { | |||
220 | CUDARuntime.reset(CreateNVCUDARuntime(*this)); | |||
221 | } | |||
222 | ||||
223 | void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) { | |||
224 | Replacements[Name] = C; | |||
225 | } | |||
226 | ||||
227 | void CodeGenModule::applyReplacements() { | |||
228 | for (auto &I : Replacements) { | |||
229 | StringRef MangledName = I.first(); | |||
230 | llvm::Constant *Replacement = I.second; | |||
231 | llvm::GlobalValue *Entry = GetGlobalValue(MangledName); | |||
232 | if (!Entry) | |||
233 | continue; | |||
234 | auto *OldF = cast<llvm::Function>(Entry); | |||
235 | auto *NewF = dyn_cast<llvm::Function>(Replacement); | |||
236 | if (!NewF) { | |||
237 | if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) { | |||
238 | NewF = dyn_cast<llvm::Function>(Alias->getAliasee()); | |||
239 | } else { | |||
240 | auto *CE = cast<llvm::ConstantExpr>(Replacement); | |||
241 | assert(CE->getOpcode() == llvm::Instruction::BitCast ||(static_cast <bool> (CE->getOpcode() == llvm::Instruction ::BitCast || CE->getOpcode() == llvm::Instruction::GetElementPtr ) ? void (0) : __assert_fail ("CE->getOpcode() == llvm::Instruction::BitCast || CE->getOpcode() == llvm::Instruction::GetElementPtr" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 242, __extension__ __PRETTY_FUNCTION__)) | |||
242 | CE->getOpcode() == llvm::Instruction::GetElementPtr)(static_cast <bool> (CE->getOpcode() == llvm::Instruction ::BitCast || CE->getOpcode() == llvm::Instruction::GetElementPtr ) ? void (0) : __assert_fail ("CE->getOpcode() == llvm::Instruction::BitCast || CE->getOpcode() == llvm::Instruction::GetElementPtr" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 242, __extension__ __PRETTY_FUNCTION__)); | |||
243 | NewF = dyn_cast<llvm::Function>(CE->getOperand(0)); | |||
244 | } | |||
245 | } | |||
246 | ||||
247 | // Replace old with new, but keep the old order. | |||
248 | OldF->replaceAllUsesWith(Replacement); | |||
249 | if (NewF) { | |||
250 | NewF->removeFromParent(); | |||
251 | OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(), | |||
252 | NewF); | |||
253 | } | |||
254 | OldF->eraseFromParent(); | |||
255 | } | |||
256 | } | |||
257 | ||||
258 | void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) { | |||
259 | GlobalValReplacements.push_back(std::make_pair(GV, C)); | |||
260 | } | |||
261 | ||||
262 | void CodeGenModule::applyGlobalValReplacements() { | |||
263 | for (auto &I : GlobalValReplacements) { | |||
264 | llvm::GlobalValue *GV = I.first; | |||
265 | llvm::Constant *C = I.second; | |||
266 | ||||
267 | GV->replaceAllUsesWith(C); | |||
268 | GV->eraseFromParent(); | |||
269 | } | |||
270 | } | |||
271 | ||||
272 | // This is only used in aliases that we created and we know they have a | |||
273 | // linear structure. | |||
274 | static const llvm::GlobalObject *getAliasedGlobal( | |||
275 | const llvm::GlobalIndirectSymbol &GIS) { | |||
276 | llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited; | |||
277 | const llvm::Constant *C = &GIS; | |||
278 | for (;;) { | |||
279 | C = C->stripPointerCasts(); | |||
280 | if (auto *GO = dyn_cast<llvm::GlobalObject>(C)) | |||
281 | return GO; | |||
282 | // stripPointerCasts will not walk over weak aliases. | |||
283 | auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C); | |||
284 | if (!GIS2) | |||
285 | return nullptr; | |||
286 | if (!Visited.insert(GIS2).second) | |||
287 | return nullptr; | |||
288 | C = GIS2->getIndirectSymbol(); | |||
289 | } | |||
290 | } | |||
291 | ||||
292 | void CodeGenModule::checkAliases() { | |||
293 | // Check if the constructed aliases are well formed. It is really unfortunate | |||
294 | // that we have to do this in CodeGen, but we only construct mangled names | |||
295 | // and aliases during codegen. | |||
296 | bool Error = false; | |||
297 | DiagnosticsEngine &Diags = getDiags(); | |||
298 | for (const GlobalDecl &GD : Aliases) { | |||
299 | const auto *D = cast<ValueDecl>(GD.getDecl()); | |||
300 | SourceLocation Location; | |||
301 | bool IsIFunc = D->hasAttr<IFuncAttr>(); | |||
302 | if (const Attr *A = D->getDefiningAttr()) | |||
303 | Location = A->getLocation(); | |||
304 | else | |||
305 | llvm_unreachable("Not an alias or ifunc?")::llvm::llvm_unreachable_internal("Not an alias or ifunc?", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 305); | |||
306 | StringRef MangledName = getMangledName(GD); | |||
307 | llvm::GlobalValue *Entry = GetGlobalValue(MangledName); | |||
308 | auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry); | |||
309 | const llvm::GlobalValue *GV = getAliasedGlobal(*Alias); | |||
310 | if (!GV) { | |||
311 | Error = true; | |||
312 | Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc; | |||
313 | } else if (GV->isDeclaration()) { | |||
314 | Error = true; | |||
315 | Diags.Report(Location, diag::err_alias_to_undefined) | |||
316 | << IsIFunc << IsIFunc; | |||
317 | } else if (IsIFunc) { | |||
318 | // Check resolver function type. | |||
319 | llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>( | |||
320 | GV->getType()->getPointerElementType()); | |||
321 | assert(FTy)(static_cast <bool> (FTy) ? void (0) : __assert_fail ("FTy" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 321, __extension__ __PRETTY_FUNCTION__)); | |||
322 | if (!FTy->getReturnType()->isPointerTy()) | |||
323 | Diags.Report(Location, diag::err_ifunc_resolver_return); | |||
324 | if (FTy->getNumParams()) | |||
325 | Diags.Report(Location, diag::err_ifunc_resolver_params); | |||
326 | } | |||
327 | ||||
328 | llvm::Constant *Aliasee = Alias->getIndirectSymbol(); | |||
329 | llvm::GlobalValue *AliaseeGV; | |||
330 | if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee)) | |||
331 | AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0)); | |||
332 | else | |||
333 | AliaseeGV = cast<llvm::GlobalValue>(Aliasee); | |||
334 | ||||
335 | if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { | |||
336 | StringRef AliasSection = SA->getName(); | |||
337 | if (AliasSection != AliaseeGV->getSection()) | |||
338 | Diags.Report(SA->getLocation(), diag::warn_alias_with_section) | |||
339 | << AliasSection << IsIFunc << IsIFunc; | |||
340 | } | |||
341 | ||||
342 | // We have to handle alias to weak aliases in here. LLVM itself disallows | |||
343 | // this since the object semantics would not match the IL one. For | |||
344 | // compatibility with gcc we implement it by just pointing the alias | |||
345 | // to its aliasee's aliasee. We also warn, since the user is probably | |||
346 | // expecting the link to be weak. | |||
347 | if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) { | |||
348 | if (GA->isInterposable()) { | |||
349 | Diags.Report(Location, diag::warn_alias_to_weak_alias) | |||
350 | << GV->getName() << GA->getName() << IsIFunc; | |||
351 | Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( | |||
352 | GA->getIndirectSymbol(), Alias->getType()); | |||
353 | Alias->setIndirectSymbol(Aliasee); | |||
354 | } | |||
355 | } | |||
356 | } | |||
357 | if (!Error) | |||
358 | return; | |||
359 | ||||
360 | for (const GlobalDecl &GD : Aliases) { | |||
361 | StringRef MangledName = getMangledName(GD); | |||
362 | llvm::GlobalValue *Entry = GetGlobalValue(MangledName); | |||
363 | auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry); | |||
364 | Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType())); | |||
365 | Alias->eraseFromParent(); | |||
366 | } | |||
367 | } | |||
368 | ||||
369 | void CodeGenModule::clear() { | |||
370 | DeferredDeclsToEmit.clear(); | |||
371 | if (OpenMPRuntime) | |||
372 | OpenMPRuntime->clear(); | |||
373 | } | |||
374 | ||||
375 | void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags, | |||
376 | StringRef MainFile) { | |||
377 | if (!hasDiagnostics()) | |||
378 | return; | |||
379 | if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) { | |||
380 | if (MainFile.empty()) | |||
381 | MainFile = "<stdin>"; | |||
382 | Diags.Report(diag::warn_profile_data_unprofiled) << MainFile; | |||
383 | } else { | |||
384 | if (Mismatched > 0) | |||
385 | Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched; | |||
386 | ||||
387 | if (Missing > 0) | |||
388 | Diags.Report(diag::warn_profile_data_missing) << Visited << Missing; | |||
389 | } | |||
390 | } | |||
391 | ||||
392 | void CodeGenModule::Release() { | |||
393 | EmitDeferred(); | |||
394 | EmitVTablesOpportunistically(); | |||
395 | applyGlobalValReplacements(); | |||
396 | applyReplacements(); | |||
397 | checkAliases(); | |||
398 | EmitCXXGlobalInitFunc(); | |||
399 | EmitCXXGlobalDtorFunc(); | |||
400 | EmitCXXThreadLocalInitFunc(); | |||
401 | if (ObjCRuntime) | |||
402 | if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) | |||
403 | AddGlobalCtor(ObjCInitFunction); | |||
404 | if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice && | |||
405 | CUDARuntime) { | |||
406 | if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction()) | |||
407 | AddGlobalCtor(CudaCtorFunction); | |||
408 | if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction()) | |||
409 | AddGlobalDtor(CudaDtorFunction); | |||
410 | } | |||
411 | if (OpenMPRuntime) | |||
412 | if (llvm::Function *OpenMPRegistrationFunction = | |||
413 | OpenMPRuntime->emitRegistrationFunction()) { | |||
414 | auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ? | |||
415 | OpenMPRegistrationFunction : nullptr; | |||
416 | AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey); | |||
417 | } | |||
418 | if (PGOReader) { | |||
419 | getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext)); | |||
420 | if (PGOStats.hasDiagnostics()) | |||
421 | PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName); | |||
422 | } | |||
423 | EmitCtorList(GlobalCtors, "llvm.global_ctors"); | |||
424 | EmitCtorList(GlobalDtors, "llvm.global_dtors"); | |||
425 | EmitGlobalAnnotations(); | |||
426 | EmitStaticExternCAliases(); | |||
427 | EmitDeferredUnusedCoverageMappings(); | |||
428 | if (CoverageMapping) | |||
429 | CoverageMapping->emit(); | |||
430 | if (CodeGenOpts.SanitizeCfiCrossDso) { | |||
431 | CodeGenFunction(*this).EmitCfiCheckFail(); | |||
432 | CodeGenFunction(*this).EmitCfiCheckStub(); | |||
433 | } | |||
434 | emitAtAvailableLinkGuard(); | |||
435 | emitLLVMUsed(); | |||
436 | if (SanStats) | |||
437 | SanStats->finish(); | |||
438 | ||||
439 | if (CodeGenOpts.Autolink && | |||
440 | (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { | |||
441 | EmitModuleLinkOptions(); | |||
442 | } | |||
443 | ||||
444 | // Record mregparm value now so it is visible through rest of codegen. | |||
445 | if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86) | |||
446 | getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters", | |||
447 | CodeGenOpts.NumRegisterParameters); | |||
448 | ||||
449 | if (CodeGenOpts.DwarfVersion) { | |||
450 | // We actually want the latest version when there are conflicts. | |||
451 | // We can change from Warning to Latest if such mode is supported. | |||
452 | getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version", | |||
453 | CodeGenOpts.DwarfVersion); | |||
454 | } | |||
455 | if (CodeGenOpts.EmitCodeView) { | |||
456 | // Indicate that we want CodeView in the metadata. | |||
457 | getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1); | |||
458 | } | |||
459 | if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) { | |||
460 | // We don't support LTO with 2 with different StrictVTablePointers | |||
461 | // FIXME: we could support it by stripping all the information introduced | |||
462 | // by StrictVTablePointers. | |||
463 | ||||
464 | getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1); | |||
465 | ||||
466 | llvm::Metadata *Ops[2] = { | |||
467 | llvm::MDString::get(VMContext, "StrictVTablePointers"), | |||
468 | llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( | |||
469 | llvm::Type::getInt32Ty(VMContext), 1))}; | |||
470 | ||||
471 | getModule().addModuleFlag(llvm::Module::Require, | |||
472 | "StrictVTablePointersRequirement", | |||
473 | llvm::MDNode::get(VMContext, Ops)); | |||
474 | } | |||
475 | if (DebugInfo) | |||
476 | // We support a single version in the linked module. The LLVM | |||
477 | // parser will drop debug info with a different version number | |||
478 | // (and warn about it, too). | |||
479 | getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version", | |||
480 | llvm::DEBUG_METADATA_VERSION); | |||
481 | ||||
482 | // We need to record the widths of enums and wchar_t, so that we can generate | |||
483 | // the correct build attributes in the ARM backend. wchar_size is also used by | |||
484 | // TargetLibraryInfo. | |||
485 | uint64_t WCharWidth = | |||
486 | Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity(); | |||
487 | getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth); | |||
488 | ||||
489 | llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); | |||
490 | if ( Arch == llvm::Triple::arm | |||
491 | || Arch == llvm::Triple::armeb | |||
492 | || Arch == llvm::Triple::thumb | |||
493 | || Arch == llvm::Triple::thumbeb) { | |||
494 | // The minimum width of an enum in bytes | |||
495 | uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4; | |||
496 | getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth); | |||
497 | } | |||
498 | ||||
499 | if (CodeGenOpts.SanitizeCfiCrossDso) { | |||
500 | // Indicate that we want cross-DSO control flow integrity checks. | |||
501 | getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1); | |||
502 | } | |||
503 | ||||
504 | if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) { | |||
505 | // Indicate whether __nvvm_reflect should be configured to flush denormal | |||
506 | // floating point values to 0. (This corresponds to its "__CUDA_FTZ" | |||
507 | // property.) | |||
508 | getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz", | |||
509 | LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0); | |||
510 | } | |||
511 | ||||
512 | // Emit OpenCL specific module metadata: OpenCL/SPIR version. | |||
513 | if (LangOpts.OpenCL) { | |||
514 | EmitOpenCLMetadata(); | |||
515 | // Emit SPIR version. | |||
516 | if (getTriple().getArch() == llvm::Triple::spir || | |||
517 | getTriple().getArch() == llvm::Triple::spir64) { | |||
518 | // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the | |||
519 | // opencl.spir.version named metadata. | |||
520 | llvm::Metadata *SPIRVerElts[] = { | |||
521 | llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( | |||
522 | Int32Ty, LangOpts.OpenCLVersion / 100)), | |||
523 | llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( | |||
524 | Int32Ty, (LangOpts.OpenCLVersion / 100 > 1) ? 0 : 2))}; | |||
525 | llvm::NamedMDNode *SPIRVerMD = | |||
526 | TheModule.getOrInsertNamedMetadata("opencl.spir.version"); | |||
527 | llvm::LLVMContext &Ctx = TheModule.getContext(); | |||
528 | SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts)); | |||
529 | } | |||
530 | } | |||
531 | ||||
532 | if (uint32_t PLevel = Context.getLangOpts().PICLevel) { | |||
533 | assert(PLevel < 3 && "Invalid PIC Level")(static_cast <bool> (PLevel < 3 && "Invalid PIC Level" ) ? void (0) : __assert_fail ("PLevel < 3 && \"Invalid PIC Level\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 533, __extension__ __PRETTY_FUNCTION__)); | |||
534 | getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel)); | |||
535 | if (Context.getLangOpts().PIE) | |||
536 | getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel)); | |||
537 | } | |||
538 | ||||
539 | SimplifyPersonality(); | |||
540 | ||||
541 | if (getCodeGenOpts().EmitDeclMetadata) | |||
542 | EmitDeclMetadata(); | |||
543 | ||||
544 | if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) | |||
545 | EmitCoverageFile(); | |||
546 | ||||
547 | if (DebugInfo) | |||
548 | DebugInfo->finalize(); | |||
549 | ||||
550 | EmitVersionIdentMetadata(); | |||
551 | ||||
552 | EmitTargetMetadata(); | |||
553 | } | |||
554 | ||||
555 | void CodeGenModule::EmitOpenCLMetadata() { | |||
556 | // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the | |||
557 | // opencl.ocl.version named metadata node. | |||
558 | llvm::Metadata *OCLVerElts[] = { | |||
559 | llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( | |||
560 | Int32Ty, LangOpts.OpenCLVersion / 100)), | |||
561 | llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( | |||
562 | Int32Ty, (LangOpts.OpenCLVersion % 100) / 10))}; | |||
563 | llvm::NamedMDNode *OCLVerMD = | |||
564 | TheModule.getOrInsertNamedMetadata("opencl.ocl.version"); | |||
565 | llvm::LLVMContext &Ctx = TheModule.getContext(); | |||
566 | OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts)); | |||
567 | } | |||
568 | ||||
569 | void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { | |||
570 | // Make sure that this type is translated. | |||
571 | Types.UpdateCompletedType(TD); | |||
572 | } | |||
573 | ||||
574 | void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) { | |||
575 | // Make sure that this type is translated. | |||
576 | Types.RefreshTypeCacheForClass(RD); | |||
577 | } | |||
578 | ||||
579 | llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) { | |||
580 | if (!TBAA) | |||
581 | return nullptr; | |||
582 | return TBAA->getTypeInfo(QTy); | |||
583 | } | |||
584 | ||||
585 | TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) { | |||
586 | // Pointee values may have incomplete types, but they shall never be | |||
587 | // dereferenced. | |||
588 | if (AccessType->isIncompleteType()) | |||
589 | return TBAAAccessInfo::getIncompleteInfo(); | |||
590 | ||||
591 | uint64_t Size = Context.getTypeSizeInChars(AccessType).getQuantity(); | |||
592 | return TBAAAccessInfo(getTBAATypeInfo(AccessType), Size); | |||
593 | } | |||
594 | ||||
595 | TBAAAccessInfo | |||
596 | CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) { | |||
597 | if (!TBAA) | |||
598 | return TBAAAccessInfo(); | |||
599 | return TBAA->getVTablePtrAccessInfo(VTablePtrType); | |||
600 | } | |||
601 | ||||
602 | llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { | |||
603 | if (!TBAA) | |||
604 | return nullptr; | |||
605 | return TBAA->getTBAAStructInfo(QTy); | |||
606 | } | |||
607 | ||||
608 | llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) { | |||
609 | if (!TBAA) | |||
610 | return nullptr; | |||
611 | return TBAA->getBaseTypeInfo(QTy); | |||
612 | } | |||
613 | ||||
614 | llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) { | |||
615 | if (!TBAA) | |||
616 | return nullptr; | |||
617 | return TBAA->getAccessTagInfo(Info); | |||
618 | } | |||
619 | ||||
620 | TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, | |||
621 | TBAAAccessInfo TargetInfo) { | |||
622 | if (!TBAA) | |||
623 | return TBAAAccessInfo(); | |||
624 | return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo); | |||
625 | } | |||
626 | ||||
627 | TBAAAccessInfo | |||
628 | CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, | |||
629 | TBAAAccessInfo InfoB) { | |||
630 | if (!TBAA) | |||
631 | return TBAAAccessInfo(); | |||
632 | return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB); | |||
633 | } | |||
634 | ||||
635 | void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst, | |||
636 | TBAAAccessInfo TBAAInfo) { | |||
637 | if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo)) | |||
638 | Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag); | |||
639 | } | |||
640 | ||||
641 | void CodeGenModule::DecorateInstructionWithInvariantGroup( | |||
642 | llvm::Instruction *I, const CXXRecordDecl *RD) { | |||
643 | I->setMetadata(llvm::LLVMContext::MD_invariant_group, | |||
644 | llvm::MDNode::get(getLLVMContext(), {})); | |||
645 | } | |||
646 | ||||
647 | void CodeGenModule::Error(SourceLocation loc, StringRef message) { | |||
648 | unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0"); | |||
649 | getDiags().Report(Context.getFullLoc(loc), diagID) << message; | |||
650 | } | |||
651 | ||||
652 | /// ErrorUnsupported - Print out an error that codegen doesn't support the | |||
653 | /// specified stmt yet. | |||
654 | void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { | |||
655 | unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, | |||
656 | "cannot compile this %0 yet"); | |||
657 | std::string Msg = Type; | |||
658 | getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) | |||
659 | << Msg << S->getSourceRange(); | |||
660 | } | |||
661 | ||||
662 | /// ErrorUnsupported - Print out an error that codegen doesn't support the | |||
663 | /// specified decl yet. | |||
664 | void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { | |||
665 | unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, | |||
666 | "cannot compile this %0 yet"); | |||
667 | std::string Msg = Type; | |||
668 | getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; | |||
669 | } | |||
670 | ||||
671 | llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { | |||
672 | return llvm::ConstantInt::get(SizeTy, size.getQuantity()); | |||
673 | } | |||
674 | ||||
675 | void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, | |||
676 | const NamedDecl *D, | |||
677 | ForDefinition_t IsForDefinition) const { | |||
678 | // Internal definitions always have default visibility. | |||
679 | if (GV->hasLocalLinkage()) { | |||
680 | GV->setVisibility(llvm::GlobalValue::DefaultVisibility); | |||
681 | return; | |||
682 | } | |||
683 | ||||
684 | // Set visibility for definitions. | |||
685 | LinkageInfo LV = D->getLinkageAndVisibility(); | |||
| ||||
686 | if (LV.isVisibilityExplicit() || | |||
687 | (IsForDefinition && !GV->hasAvailableExternallyLinkage())) | |||
688 | GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); | |||
689 | } | |||
690 | ||||
691 | static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { | |||
692 | return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) | |||
693 | .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) | |||
694 | .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) | |||
695 | .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) | |||
696 | .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); | |||
697 | } | |||
698 | ||||
699 | static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel( | |||
700 | CodeGenOptions::TLSModel M) { | |||
701 | switch (M) { | |||
702 | case CodeGenOptions::GeneralDynamicTLSModel: | |||
703 | return llvm::GlobalVariable::GeneralDynamicTLSModel; | |||
704 | case CodeGenOptions::LocalDynamicTLSModel: | |||
705 | return llvm::GlobalVariable::LocalDynamicTLSModel; | |||
706 | case CodeGenOptions::InitialExecTLSModel: | |||
707 | return llvm::GlobalVariable::InitialExecTLSModel; | |||
708 | case CodeGenOptions::LocalExecTLSModel: | |||
709 | return llvm::GlobalVariable::LocalExecTLSModel; | |||
710 | } | |||
711 | llvm_unreachable("Invalid TLS model!")::llvm::llvm_unreachable_internal("Invalid TLS model!", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 711); | |||
712 | } | |||
713 | ||||
714 | void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const { | |||
715 | assert(D.getTLSKind() && "setting TLS mode on non-TLS var!")(static_cast <bool> (D.getTLSKind() && "setting TLS mode on non-TLS var!" ) ? void (0) : __assert_fail ("D.getTLSKind() && \"setting TLS mode on non-TLS var!\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 715, __extension__ __PRETTY_FUNCTION__)); | |||
716 | ||||
717 | llvm::GlobalValue::ThreadLocalMode TLM; | |||
718 | TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel()); | |||
719 | ||||
720 | // Override the TLS model if it is explicitly specified. | |||
721 | if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { | |||
722 | TLM = GetLLVMTLSModel(Attr->getModel()); | |||
723 | } | |||
724 | ||||
725 | GV->setThreadLocalMode(TLM); | |||
726 | } | |||
727 | ||||
728 | StringRef CodeGenModule::getMangledName(GlobalDecl GD) { | |||
729 | GlobalDecl CanonicalGD = GD.getCanonicalDecl(); | |||
730 | ||||
731 | // Some ABIs don't have constructor variants. Make sure that base and | |||
732 | // complete constructors get mangled the same. | |||
733 | if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) { | |||
734 | if (!getTarget().getCXXABI().hasConstructorVariants()) { | |||
735 | CXXCtorType OrigCtorType = GD.getCtorType(); | |||
736 | assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete)(static_cast <bool> (OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete) ? void (0) : __assert_fail ("OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 736, __extension__ __PRETTY_FUNCTION__)); | |||
737 | if (OrigCtorType == Ctor_Base) | |||
738 | CanonicalGD = GlobalDecl(CD, Ctor_Complete); | |||
739 | } | |||
740 | } | |||
741 | ||||
742 | auto FoundName = MangledDeclNames.find(CanonicalGD); | |||
743 | if (FoundName != MangledDeclNames.end()) | |||
744 | return FoundName->second; | |||
745 | ||||
746 | const auto *ND = cast<NamedDecl>(GD.getDecl()); | |||
747 | SmallString<256> Buffer; | |||
748 | StringRef Str; | |||
749 | if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) { | |||
750 | llvm::raw_svector_ostream Out(Buffer); | |||
751 | if (const auto *D = dyn_cast<CXXConstructorDecl>(ND)) | |||
752 | getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out); | |||
753 | else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND)) | |||
754 | getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out); | |||
755 | else | |||
756 | getCXXABI().getMangleContext().mangleName(ND, Out); | |||
757 | Str = Out.str(); | |||
758 | } else { | |||
759 | IdentifierInfo *II = ND->getIdentifier(); | |||
760 | assert(II && "Attempt to mangle unnamed decl.")(static_cast <bool> (II && "Attempt to mangle unnamed decl." ) ? void (0) : __assert_fail ("II && \"Attempt to mangle unnamed decl.\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 760, __extension__ __PRETTY_FUNCTION__)); | |||
761 | const auto *FD = dyn_cast<FunctionDecl>(ND); | |||
762 | ||||
763 | if (FD && | |||
764 | FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) { | |||
765 | llvm::raw_svector_ostream Out(Buffer); | |||
766 | Out << "__regcall3__" << II->getName(); | |||
767 | Str = Out.str(); | |||
768 | } else { | |||
769 | Str = II->getName(); | |||
770 | } | |||
771 | } | |||
772 | ||||
773 | // Keep the first result in the case of a mangling collision. | |||
774 | auto Result = Manglings.insert(std::make_pair(Str, GD)); | |||
775 | return MangledDeclNames[CanonicalGD] = Result.first->first(); | |||
776 | } | |||
777 | ||||
778 | StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, | |||
779 | const BlockDecl *BD) { | |||
780 | MangleContext &MangleCtx = getCXXABI().getMangleContext(); | |||
781 | const Decl *D = GD.getDecl(); | |||
782 | ||||
783 | SmallString<256> Buffer; | |||
784 | llvm::raw_svector_ostream Out(Buffer); | |||
785 | if (!D) | |||
786 | MangleCtx.mangleGlobalBlock(BD, | |||
787 | dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); | |||
788 | else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) | |||
789 | MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); | |||
790 | else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) | |||
791 | MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); | |||
792 | else | |||
793 | MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); | |||
794 | ||||
795 | auto Result = Manglings.insert(std::make_pair(Out.str(), BD)); | |||
796 | return Result.first->first(); | |||
797 | } | |||
798 | ||||
799 | llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { | |||
800 | return getModule().getNamedValue(Name); | |||
801 | } | |||
802 | ||||
803 | /// AddGlobalCtor - Add a function to the list that will be called before | |||
804 | /// main() runs. | |||
805 | void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, | |||
806 | llvm::Constant *AssociatedData) { | |||
807 | // FIXME: Type coercion of void()* types. | |||
808 | GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData)); | |||
809 | } | |||
810 | ||||
811 | /// AddGlobalDtor - Add a function to the list that will be called | |||
812 | /// when the module is unloaded. | |||
813 | void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) { | |||
814 | // FIXME: Type coercion of void()* types. | |||
815 | GlobalDtors.push_back(Structor(Priority, Dtor, nullptr)); | |||
816 | } | |||
817 | ||||
818 | void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) { | |||
819 | if (Fns.empty()) return; | |||
820 | ||||
821 | // Ctor function type is void()*. | |||
822 | llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); | |||
823 | llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); | |||
824 | ||||
825 | // Get the type of a ctor entry, { i32, void ()*, i8* }. | |||
826 | llvm::StructType *CtorStructTy = llvm::StructType::get( | |||
827 | Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy); | |||
828 | ||||
829 | // Construct the constructor and destructor arrays. | |||
830 | ConstantInitBuilder builder(*this); | |||
831 | auto ctors = builder.beginArray(CtorStructTy); | |||
832 | for (const auto &I : Fns) { | |||
833 | auto ctor = ctors.beginStruct(CtorStructTy); | |||
834 | ctor.addInt(Int32Ty, I.Priority); | |||
835 | ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy)); | |||
836 | if (I.AssociatedData) | |||
837 | ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy)); | |||
838 | else | |||
839 | ctor.addNullPointer(VoidPtrTy); | |||
840 | ctor.finishAndAddTo(ctors); | |||
841 | } | |||
842 | ||||
843 | auto list = | |||
844 | ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(), | |||
845 | /*constant*/ false, | |||
846 | llvm::GlobalValue::AppendingLinkage); | |||
847 | ||||
848 | // The LTO linker doesn't seem to like it when we set an alignment | |||
849 | // on appending variables. Take it off as a workaround. | |||
850 | list->setAlignment(0); | |||
851 | ||||
852 | Fns.clear(); | |||
853 | } | |||
854 | ||||
855 | llvm::GlobalValue::LinkageTypes | |||
856 | CodeGenModule::getFunctionLinkage(GlobalDecl GD) { | |||
857 | const auto *D = cast<FunctionDecl>(GD.getDecl()); | |||
858 | ||||
859 | GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); | |||
860 | ||||
861 | if (isa<CXXDestructorDecl>(D) && | |||
862 | getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), | |||
863 | GD.getDtorType())) { | |||
864 | // Destructor variants in the Microsoft C++ ABI are always internal or | |||
865 | // linkonce_odr thunks emitted on an as-needed basis. | |||
866 | return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage | |||
867 | : llvm::GlobalValue::LinkOnceODRLinkage; | |||
868 | } | |||
869 | ||||
870 | if (isa<CXXConstructorDecl>(D) && | |||
871 | cast<CXXConstructorDecl>(D)->isInheritingConstructor() && | |||
872 | Context.getTargetInfo().getCXXABI().isMicrosoft()) { | |||
873 | // Our approach to inheriting constructors is fundamentally different from | |||
874 | // that used by the MS ABI, so keep our inheriting constructor thunks | |||
875 | // internal rather than trying to pick an unambiguous mangling for them. | |||
876 | return llvm::GlobalValue::InternalLinkage; | |||
877 | } | |||
878 | ||||
879 | return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false); | |||
880 | } | |||
881 | ||||
882 | void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) { | |||
883 | const auto *FD = cast<FunctionDecl>(GD.getDecl()); | |||
884 | ||||
885 | if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) { | |||
886 | if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) { | |||
887 | // Don't dllexport/import destructor thunks. | |||
888 | F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); | |||
889 | return; | |||
890 | } | |||
891 | } | |||
892 | ||||
893 | if (FD->hasAttr<DLLImportAttr>()) | |||
894 | F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); | |||
895 | else if (FD->hasAttr<DLLExportAttr>()) | |||
896 | F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); | |||
897 | else | |||
898 | F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); | |||
899 | } | |||
900 | ||||
901 | llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) { | |||
902 | llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD); | |||
903 | if (!MDS) return nullptr; | |||
904 | ||||
905 | return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString())); | |||
906 | } | |||
907 | ||||
908 | void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D, | |||
909 | llvm::Function *F) { | |||
910 | setNonAliasAttributes(D, F); | |||
911 | } | |||
912 | ||||
913 | void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, | |||
914 | const CGFunctionInfo &Info, | |||
915 | llvm::Function *F) { | |||
916 | unsigned CallingConv; | |||
917 | llvm::AttributeList PAL; | |||
918 | ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false); | |||
919 | F->setAttributes(PAL); | |||
920 | F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); | |||
921 | } | |||
922 | ||||
923 | /// Determines whether the language options require us to model | |||
924 | /// unwind exceptions. We treat -fexceptions as mandating this | |||
925 | /// except under the fragile ObjC ABI with only ObjC exceptions | |||
926 | /// enabled. This means, for example, that C with -fexceptions | |||
927 | /// enables this. | |||
928 | static bool hasUnwindExceptions(const LangOptions &LangOpts) { | |||
929 | // If exceptions are completely disabled, obviously this is false. | |||
930 | if (!LangOpts.Exceptions) return false; | |||
931 | ||||
932 | // If C++ exceptions are enabled, this is true. | |||
933 | if (LangOpts.CXXExceptions) return true; | |||
934 | ||||
935 | // If ObjC exceptions are enabled, this depends on the ABI. | |||
936 | if (LangOpts.ObjCExceptions) { | |||
937 | return LangOpts.ObjCRuntime.hasUnwindExceptions(); | |||
938 | } | |||
939 | ||||
940 | return true; | |||
941 | } | |||
942 | ||||
943 | void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, | |||
944 | llvm::Function *F) { | |||
945 | llvm::AttrBuilder B; | |||
946 | ||||
947 | if (CodeGenOpts.UnwindTables) | |||
948 | B.addAttribute(llvm::Attribute::UWTable); | |||
949 | ||||
950 | if (!hasUnwindExceptions(LangOpts)) | |||
951 | B.addAttribute(llvm::Attribute::NoUnwind); | |||
952 | ||||
953 | if (LangOpts.getStackProtector() == LangOptions::SSPOn) | |||
954 | B.addAttribute(llvm::Attribute::StackProtect); | |||
955 | else if (LangOpts.getStackProtector() == LangOptions::SSPStrong) | |||
956 | B.addAttribute(llvm::Attribute::StackProtectStrong); | |||
957 | else if (LangOpts.getStackProtector() == LangOptions::SSPReq) | |||
958 | B.addAttribute(llvm::Attribute::StackProtectReq); | |||
959 | ||||
960 | if (!D) { | |||
961 | // If we don't have a declaration to control inlining, the function isn't | |||
962 | // explicitly marked as alwaysinline for semantic reasons, and inlining is | |||
963 | // disabled, mark the function as noinline. | |||
964 | if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && | |||
965 | CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) | |||
966 | B.addAttribute(llvm::Attribute::NoInline); | |||
967 | ||||
968 | F->addAttributes(llvm::AttributeList::FunctionIndex, B); | |||
969 | return; | |||
970 | } | |||
971 | ||||
972 | // Track whether we need to add the optnone LLVM attribute, | |||
973 | // starting with the default for this optimization level. | |||
974 | bool ShouldAddOptNone = | |||
975 | !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0; | |||
976 | // We can't add optnone in the following cases, it won't pass the verifier. | |||
977 | ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>(); | |||
978 | ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline); | |||
979 | ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>(); | |||
980 | ||||
981 | if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) { | |||
982 | B.addAttribute(llvm::Attribute::OptimizeNone); | |||
983 | ||||
984 | // OptimizeNone implies noinline; we should not be inlining such functions. | |||
985 | B.addAttribute(llvm::Attribute::NoInline); | |||
986 | assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&(static_cast <bool> (!F->hasFnAttribute(llvm::Attribute ::AlwaysInline) && "OptimizeNone and AlwaysInline on same function!" ) ? void (0) : __assert_fail ("!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && \"OptimizeNone and AlwaysInline on same function!\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 987, __extension__ __PRETTY_FUNCTION__)) | |||
987 | "OptimizeNone and AlwaysInline on same function!")(static_cast <bool> (!F->hasFnAttribute(llvm::Attribute ::AlwaysInline) && "OptimizeNone and AlwaysInline on same function!" ) ? void (0) : __assert_fail ("!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && \"OptimizeNone and AlwaysInline on same function!\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 987, __extension__ __PRETTY_FUNCTION__)); | |||
988 | ||||
989 | // We still need to handle naked functions even though optnone subsumes | |||
990 | // much of their semantics. | |||
991 | if (D->hasAttr<NakedAttr>()) | |||
992 | B.addAttribute(llvm::Attribute::Naked); | |||
993 | ||||
994 | // OptimizeNone wins over OptimizeForSize and MinSize. | |||
995 | F->removeFnAttr(llvm::Attribute::OptimizeForSize); | |||
996 | F->removeFnAttr(llvm::Attribute::MinSize); | |||
997 | } else if (D->hasAttr<NakedAttr>()) { | |||
998 | // Naked implies noinline: we should not be inlining such functions. | |||
999 | B.addAttribute(llvm::Attribute::Naked); | |||
1000 | B.addAttribute(llvm::Attribute::NoInline); | |||
1001 | } else if (D->hasAttr<NoDuplicateAttr>()) { | |||
1002 | B.addAttribute(llvm::Attribute::NoDuplicate); | |||
1003 | } else if (D->hasAttr<NoInlineAttr>()) { | |||
1004 | B.addAttribute(llvm::Attribute::NoInline); | |||
1005 | } else if (D->hasAttr<AlwaysInlineAttr>() && | |||
1006 | !F->hasFnAttribute(llvm::Attribute::NoInline)) { | |||
1007 | // (noinline wins over always_inline, and we can't specify both in IR) | |||
1008 | B.addAttribute(llvm::Attribute::AlwaysInline); | |||
1009 | } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) { | |||
1010 | // If we're not inlining, then force everything that isn't always_inline to | |||
1011 | // carry an explicit noinline attribute. | |||
1012 | if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline)) | |||
1013 | B.addAttribute(llvm::Attribute::NoInline); | |||
1014 | } else { | |||
1015 | // Otherwise, propagate the inline hint attribute and potentially use its | |||
1016 | // absence to mark things as noinline. | |||
1017 | if (auto *FD = dyn_cast<FunctionDecl>(D)) { | |||
1018 | if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) { | |||
1019 | return Redecl->isInlineSpecified(); | |||
1020 | })) { | |||
1021 | B.addAttribute(llvm::Attribute::InlineHint); | |||
1022 | } else if (CodeGenOpts.getInlining() == | |||
1023 | CodeGenOptions::OnlyHintInlining && | |||
1024 | !FD->isInlined() && | |||
1025 | !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { | |||
1026 | B.addAttribute(llvm::Attribute::NoInline); | |||
1027 | } | |||
1028 | } | |||
1029 | } | |||
1030 | ||||
1031 | // Add other optimization related attributes if we are optimizing this | |||
1032 | // function. | |||
1033 | if (!D->hasAttr<OptimizeNoneAttr>()) { | |||
1034 | if (D->hasAttr<ColdAttr>()) { | |||
1035 | if (!ShouldAddOptNone) | |||
1036 | B.addAttribute(llvm::Attribute::OptimizeForSize); | |||
1037 | B.addAttribute(llvm::Attribute::Cold); | |||
1038 | } | |||
1039 | ||||
1040 | if (D->hasAttr<MinSizeAttr>()) | |||
1041 | B.addAttribute(llvm::Attribute::MinSize); | |||
1042 | } | |||
1043 | ||||
1044 | F->addAttributes(llvm::AttributeList::FunctionIndex, B); | |||
1045 | ||||
1046 | unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); | |||
1047 | if (alignment) | |||
1048 | F->setAlignment(alignment); | |||
1049 | ||||
1050 | // Some C++ ABIs require 2-byte alignment for member functions, in order to | |||
1051 | // reserve a bit for differentiating between virtual and non-virtual member | |||
1052 | // functions. If the current target's C++ ABI requires this and this is a | |||
1053 | // member function, set its alignment accordingly. | |||
1054 | if (getTarget().getCXXABI().areMemberFunctionsAligned()) { | |||
1055 | if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) | |||
1056 | F->setAlignment(2); | |||
1057 | } | |||
1058 | ||||
1059 | // In the cross-dso CFI mode, we want !type attributes on definitions only. | |||
1060 | if (CodeGenOpts.SanitizeCfiCrossDso) | |||
1061 | if (auto *FD = dyn_cast<FunctionDecl>(D)) | |||
1062 | CreateFunctionTypeMetadata(FD, F); | |||
1063 | } | |||
1064 | ||||
1065 | void CodeGenModule::SetCommonAttributes(const Decl *D, | |||
1066 | llvm::GlobalValue *GV) { | |||
1067 | if (const auto *ND = dyn_cast_or_null<NamedDecl>(D)) | |||
1068 | setGlobalVisibility(GV, ND, ForDefinition); | |||
1069 | else | |||
1070 | GV->setVisibility(llvm::GlobalValue::DefaultVisibility); | |||
1071 | ||||
1072 | if (D && D->hasAttr<UsedAttr>()) | |||
1073 | addUsedGlobal(GV); | |||
1074 | } | |||
1075 | ||||
1076 | void CodeGenModule::setAliasAttributes(const Decl *D, | |||
1077 | llvm::GlobalValue *GV) { | |||
1078 | SetCommonAttributes(D, GV); | |||
1079 | ||||
1080 | // Process the dllexport attribute based on whether the original definition | |||
1081 | // (not necessarily the aliasee) was exported. | |||
1082 | if (D->hasAttr<DLLExportAttr>()) | |||
1083 | GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); | |||
1084 | } | |||
1085 | ||||
1086 | void CodeGenModule::setNonAliasAttributes(const Decl *D, | |||
1087 | llvm::GlobalObject *GO) { | |||
1088 | SetCommonAttributes(D, GO); | |||
1089 | ||||
1090 | if (D) { | |||
1091 | if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) { | |||
1092 | if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>()) | |||
1093 | GV->addAttribute("bss-section", SA->getName()); | |||
1094 | if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>()) | |||
1095 | GV->addAttribute("data-section", SA->getName()); | |||
1096 | if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>()) | |||
1097 | GV->addAttribute("rodata-section", SA->getName()); | |||
1098 | } | |||
1099 | ||||
1100 | if (auto *F = dyn_cast<llvm::Function>(GO)) { | |||
1101 | if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>()) | |||
1102 | if (!D->getAttr<SectionAttr>()) | |||
1103 | F->addFnAttr("implicit-section-name", SA->getName()); | |||
1104 | } | |||
1105 | ||||
1106 | if (const SectionAttr *SA = D->getAttr<SectionAttr>()) | |||
1107 | GO->setSection(SA->getName()); | |||
1108 | } | |||
1109 | ||||
1110 | getTargetCodeGenInfo().setTargetAttributes(D, GO, *this, ForDefinition); | |||
1111 | } | |||
1112 | ||||
1113 | void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, | |||
1114 | llvm::Function *F, | |||
1115 | const CGFunctionInfo &FI) { | |||
1116 | SetLLVMFunctionAttributes(D, FI, F); | |||
1117 | SetLLVMFunctionAttributesForDefinition(D, F); | |||
1118 | ||||
1119 | F->setLinkage(llvm::Function::InternalLinkage); | |||
1120 | ||||
1121 | setNonAliasAttributes(D, F); | |||
1122 | } | |||
1123 | ||||
1124 | static void setLinkageForGV(llvm::GlobalValue *GV, | |||
1125 | const NamedDecl *ND) { | |||
1126 | // Set linkage and visibility in case we never see a definition. | |||
1127 | LinkageInfo LV = ND->getLinkageAndVisibility(); | |||
1128 | if (!isExternallyVisible(LV.getLinkage())) { | |||
1129 | // Don't set internal linkage on declarations. | |||
1130 | } else { | |||
1131 | if (ND->hasAttr<DLLImportAttr>()) { | |||
1132 | GV->setLinkage(llvm::GlobalValue::ExternalLinkage); | |||
1133 | GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); | |||
1134 | } else if (ND->hasAttr<DLLExportAttr>()) { | |||
1135 | GV->setLinkage(llvm::GlobalValue::ExternalLinkage); | |||
1136 | } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) { | |||
1137 | // "extern_weak" is overloaded in LLVM; we probably should have | |||
1138 | // separate linkage types for this. | |||
1139 | GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); | |||
1140 | } | |||
1141 | } | |||
1142 | } | |||
1143 | ||||
1144 | void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD, | |||
1145 | llvm::Function *F) { | |||
1146 | // Only if we are checking indirect calls. | |||
1147 | if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall)) | |||
1148 | return; | |||
1149 | ||||
1150 | // Non-static class methods are handled via vtable pointer checks elsewhere. | |||
1151 | if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) | |||
1152 | return; | |||
1153 | ||||
1154 | // Additionally, if building with cross-DSO support... | |||
1155 | if (CodeGenOpts.SanitizeCfiCrossDso) { | |||
1156 | // Skip available_externally functions. They won't be codegen'ed in the | |||
1157 | // current module anyway. | |||
1158 | if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally) | |||
1159 | return; | |||
1160 | } | |||
1161 | ||||
1162 | llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType()); | |||
1163 | F->addTypeMetadata(0, MD); | |||
1164 | F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType())); | |||
1165 | ||||
1166 | // Emit a hash-based bit set entry for cross-DSO calls. | |||
1167 | if (CodeGenOpts.SanitizeCfiCrossDso) | |||
1168 | if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) | |||
1169 | F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId)); | |||
1170 | } | |||
1171 | ||||
1172 | void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, | |||
1173 | bool IsIncompleteFunction, | |||
1174 | bool IsThunk, | |||
1175 | ForDefinition_t IsForDefinition) { | |||
1176 | ||||
1177 | if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) { | |||
1178 | // If this is an intrinsic function, set the function's attributes | |||
1179 | // to the intrinsic's attributes. | |||
1180 | F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID)); | |||
1181 | return; | |||
1182 | } | |||
1183 | ||||
1184 | const auto *FD = cast<FunctionDecl>(GD.getDecl()); | |||
1185 | ||||
1186 | if (!IsIncompleteFunction) { | |||
1187 | SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F); | |||
1188 | // Setup target-specific attributes. | |||
1189 | if (!IsForDefinition) | |||
1190 | getTargetCodeGenInfo().setTargetAttributes(FD, F, *this, | |||
1191 | NotForDefinition); | |||
1192 | } | |||
1193 | ||||
1194 | // Add the Returned attribute for "this", except for iOS 5 and earlier | |||
1195 | // where substantial code, including the libstdc++ dylib, was compiled with | |||
1196 | // GCC and does not actually return "this". | |||
1197 | if (!IsThunk && getCXXABI().HasThisReturn(GD) && | |||
1198 | !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) { | |||
1199 | assert(!F->arg_empty() &&(static_cast <bool> (!F->arg_empty() && F-> arg_begin()->getType() ->canLosslesslyBitCastTo(F->getReturnType ()) && "unexpected this return") ? void (0) : __assert_fail ("!F->arg_empty() && F->arg_begin()->getType() ->canLosslesslyBitCastTo(F->getReturnType()) && \"unexpected this return\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 1202, __extension__ __PRETTY_FUNCTION__)) | |||
1200 | F->arg_begin()->getType()(static_cast <bool> (!F->arg_empty() && F-> arg_begin()->getType() ->canLosslesslyBitCastTo(F->getReturnType ()) && "unexpected this return") ? void (0) : __assert_fail ("!F->arg_empty() && F->arg_begin()->getType() ->canLosslesslyBitCastTo(F->getReturnType()) && \"unexpected this return\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 1202, __extension__ __PRETTY_FUNCTION__)) | |||
1201 | ->canLosslesslyBitCastTo(F->getReturnType()) &&(static_cast <bool> (!F->arg_empty() && F-> arg_begin()->getType() ->canLosslesslyBitCastTo(F->getReturnType ()) && "unexpected this return") ? void (0) : __assert_fail ("!F->arg_empty() && F->arg_begin()->getType() ->canLosslesslyBitCastTo(F->getReturnType()) && \"unexpected this return\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 1202, __extension__ __PRETTY_FUNCTION__)) | |||
1202 | "unexpected this return")(static_cast <bool> (!F->arg_empty() && F-> arg_begin()->getType() ->canLosslesslyBitCastTo(F->getReturnType ()) && "unexpected this return") ? void (0) : __assert_fail ("!F->arg_empty() && F->arg_begin()->getType() ->canLosslesslyBitCastTo(F->getReturnType()) && \"unexpected this return\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 1202, __extension__ __PRETTY_FUNCTION__)); | |||
1203 | F->addAttribute(1, llvm::Attribute::Returned); | |||
1204 | } | |||
1205 | ||||
1206 | // Only a few attributes are set on declarations; these may later be | |||
1207 | // overridden by a definition. | |||
1208 | ||||
1209 | setLinkageForGV(F, FD); | |||
1210 | setGlobalVisibility(F, FD, NotForDefinition); | |||
1211 | ||||
1212 | if (FD->getAttr<PragmaClangTextSectionAttr>()) { | |||
1213 | F->addFnAttr("implicit-section-name"); | |||
1214 | } | |||
1215 | ||||
1216 | if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) | |||
1217 | F->setSection(SA->getName()); | |||
1218 | ||||
1219 | if (FD->isReplaceableGlobalAllocationFunction()) { | |||
1220 | // A replaceable global allocation function does not act like a builtin by | |||
1221 | // default, only if it is invoked by a new-expression or delete-expression. | |||
1222 | F->addAttribute(llvm::AttributeList::FunctionIndex, | |||
1223 | llvm::Attribute::NoBuiltin); | |||
1224 | ||||
1225 | // A sane operator new returns a non-aliasing pointer. | |||
1226 | // FIXME: Also add NonNull attribute to the return value | |||
1227 | // for the non-nothrow forms? | |||
1228 | auto Kind = FD->getDeclName().getCXXOverloadedOperator(); | |||
1229 | if (getCodeGenOpts().AssumeSaneOperatorNew && | |||
1230 | (Kind == OO_New || Kind == OO_Array_New)) | |||
1231 | F->addAttribute(llvm::AttributeList::ReturnIndex, | |||
1232 | llvm::Attribute::NoAlias); | |||
1233 | } | |||
1234 | ||||
1235 | if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD)) | |||
1236 | F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); | |||
1237 | else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) | |||
1238 | if (MD->isVirtual()) | |||
1239 | F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); | |||
1240 | ||||
1241 | // Don't emit entries for function declarations in the cross-DSO mode. This | |||
1242 | // is handled with better precision by the receiving DSO. | |||
1243 | if (!CodeGenOpts.SanitizeCfiCrossDso) | |||
1244 | CreateFunctionTypeMetadata(FD, F); | |||
1245 | ||||
1246 | if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>()) | |||
1247 | getOpenMPRuntime().emitDeclareSimdFunction(FD, F); | |||
1248 | } | |||
1249 | ||||
1250 | void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { | |||
1251 | assert(!GV->isDeclaration() &&(static_cast <bool> (!GV->isDeclaration() && "Only globals with definition can force usage.") ? void (0) : __assert_fail ("!GV->isDeclaration() && \"Only globals with definition can force usage.\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 1252, __extension__ __PRETTY_FUNCTION__)) | |||
1252 | "Only globals with definition can force usage.")(static_cast <bool> (!GV->isDeclaration() && "Only globals with definition can force usage.") ? void (0) : __assert_fail ("!GV->isDeclaration() && \"Only globals with definition can force usage.\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 1252, __extension__ __PRETTY_FUNCTION__)); | |||
1253 | LLVMUsed.emplace_back(GV); | |||
1254 | } | |||
1255 | ||||
1256 | void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { | |||
1257 | assert(!GV->isDeclaration() &&(static_cast <bool> (!GV->isDeclaration() && "Only globals with definition can force usage.") ? void (0) : __assert_fail ("!GV->isDeclaration() && \"Only globals with definition can force usage.\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 1258, __extension__ __PRETTY_FUNCTION__)) | |||
1258 | "Only globals with definition can force usage.")(static_cast <bool> (!GV->isDeclaration() && "Only globals with definition can force usage.") ? void (0) : __assert_fail ("!GV->isDeclaration() && \"Only globals with definition can force usage.\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 1258, __extension__ __PRETTY_FUNCTION__)); | |||
1259 | LLVMCompilerUsed.emplace_back(GV); | |||
1260 | } | |||
1261 | ||||
1262 | static void emitUsed(CodeGenModule &CGM, StringRef Name, | |||
1263 | std::vector<llvm::WeakTrackingVH> &List) { | |||
1264 | // Don't create llvm.used if there is no need. | |||
1265 | if (List.empty()) | |||
1266 | return; | |||
1267 | ||||
1268 | // Convert List to what ConstantArray needs. | |||
1269 | SmallVector<llvm::Constant*, 8> UsedArray; | |||
1270 | UsedArray.resize(List.size()); | |||
1271 | for (unsigned i = 0, e = List.size(); i != e; ++i) { | |||
1272 | UsedArray[i] = | |||
1273 | llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( | |||
1274 | cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy); | |||
1275 | } | |||
1276 | ||||
1277 | if (UsedArray.empty()) | |||
1278 | return; | |||
1279 | llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); | |||
1280 | ||||
1281 | auto *GV = new llvm::GlobalVariable( | |||
1282 | CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, | |||
1283 | llvm::ConstantArray::get(ATy, UsedArray), Name); | |||
1284 | ||||
1285 | GV->setSection("llvm.metadata"); | |||
1286 | } | |||
1287 | ||||
1288 | void CodeGenModule::emitLLVMUsed() { | |||
1289 | emitUsed(*this, "llvm.used", LLVMUsed); | |||
1290 | emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); | |||
1291 | } | |||
1292 | ||||
1293 | void CodeGenModule::AppendLinkerOptions(StringRef Opts) { | |||
1294 | auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); | |||
1295 | LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); | |||
1296 | } | |||
1297 | ||||
1298 | void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { | |||
1299 | llvm::SmallString<32> Opt; | |||
1300 | getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); | |||
1301 | auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); | |||
1302 | LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); | |||
1303 | } | |||
1304 | ||||
1305 | void CodeGenModule::AddDependentLib(StringRef Lib) { | |||
1306 | llvm::SmallString<24> Opt; | |||
1307 | getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); | |||
1308 | auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); | |||
1309 | LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); | |||
1310 | } | |||
1311 | ||||
1312 | /// \brief Add link options implied by the given module, including modules | |||
1313 | /// it depends on, using a postorder walk. | |||
1314 | static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, | |||
1315 | SmallVectorImpl<llvm::MDNode *> &Metadata, | |||
1316 | llvm::SmallPtrSet<Module *, 16> &Visited) { | |||
1317 | // Import this module's parent. | |||
1318 | if (Mod->Parent && Visited.insert(Mod->Parent).second) { | |||
1319 | addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); | |||
1320 | } | |||
1321 | ||||
1322 | // Import this module's dependencies. | |||
1323 | for (unsigned I = Mod->Imports.size(); I > 0; --I) { | |||
1324 | if (Visited.insert(Mod->Imports[I - 1]).second) | |||
1325 | addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited); | |||
1326 | } | |||
1327 | ||||
1328 | // Add linker options to link against the libraries/frameworks | |||
1329 | // described by this module. | |||
1330 | llvm::LLVMContext &Context = CGM.getLLVMContext(); | |||
1331 | for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) { | |||
1332 | // Link against a framework. Frameworks are currently Darwin only, so we | |||
1333 | // don't to ask TargetCodeGenInfo for the spelling of the linker option. | |||
1334 | if (Mod->LinkLibraries[I-1].IsFramework) { | |||
1335 | llvm::Metadata *Args[2] = { | |||
1336 | llvm::MDString::get(Context, "-framework"), | |||
1337 | llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)}; | |||
1338 | ||||
1339 | Metadata.push_back(llvm::MDNode::get(Context, Args)); | |||
1340 | continue; | |||
1341 | } | |||
1342 | ||||
1343 | // Link against a library. | |||
1344 | llvm::SmallString<24> Opt; | |||
1345 | CGM.getTargetCodeGenInfo().getDependentLibraryOption( | |||
1346 | Mod->LinkLibraries[I-1].Library, Opt); | |||
1347 | auto *OptString = llvm::MDString::get(Context, Opt); | |||
1348 | Metadata.push_back(llvm::MDNode::get(Context, OptString)); | |||
1349 | } | |||
1350 | } | |||
1351 | ||||
1352 | void CodeGenModule::EmitModuleLinkOptions() { | |||
1353 | // Collect the set of all of the modules we want to visit to emit link | |||
1354 | // options, which is essentially the imported modules and all of their | |||
1355 | // non-explicit child modules. | |||
1356 | llvm::SetVector<clang::Module *> LinkModules; | |||
1357 | llvm::SmallPtrSet<clang::Module *, 16> Visited; | |||
1358 | SmallVector<clang::Module *, 16> Stack; | |||
1359 | ||||
1360 | // Seed the stack with imported modules. | |||
1361 | for (Module *M : ImportedModules) { | |||
1362 | // Do not add any link flags when an implementation TU of a module imports | |||
1363 | // a header of that same module. | |||
1364 | if (M->getTopLevelModuleName() == getLangOpts().CurrentModule && | |||
1365 | !getLangOpts().isCompilingModule()) | |||
1366 | continue; | |||
1367 | if (Visited.insert(M).second) | |||
1368 | Stack.push_back(M); | |||
1369 | } | |||
1370 | ||||
1371 | // Find all of the modules to import, making a little effort to prune | |||
1372 | // non-leaf modules. | |||
1373 | while (!Stack.empty()) { | |||
1374 | clang::Module *Mod = Stack.pop_back_val(); | |||
1375 | ||||
1376 | bool AnyChildren = false; | |||
1377 | ||||
1378 | // Visit the submodules of this module. | |||
1379 | for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), | |||
1380 | SubEnd = Mod->submodule_end(); | |||
1381 | Sub != SubEnd; ++Sub) { | |||
1382 | // Skip explicit children; they need to be explicitly imported to be | |||
1383 | // linked against. | |||
1384 | if ((*Sub)->IsExplicit) | |||
1385 | continue; | |||
1386 | ||||
1387 | if (Visited.insert(*Sub).second) { | |||
1388 | Stack.push_back(*Sub); | |||
1389 | AnyChildren = true; | |||
1390 | } | |||
1391 | } | |||
1392 | ||||
1393 | // We didn't find any children, so add this module to the list of | |||
1394 | // modules to link against. | |||
1395 | if (!AnyChildren) { | |||
1396 | LinkModules.insert(Mod); | |||
1397 | } | |||
1398 | } | |||
1399 | ||||
1400 | // Add link options for all of the imported modules in reverse topological | |||
1401 | // order. We don't do anything to try to order import link flags with respect | |||
1402 | // to linker options inserted by things like #pragma comment(). | |||
1403 | SmallVector<llvm::MDNode *, 16> MetadataArgs; | |||
1404 | Visited.clear(); | |||
1405 | for (Module *M : LinkModules) | |||
1406 | if (Visited.insert(M).second) | |||
1407 | addLinkOptionsPostorder(*this, M, MetadataArgs, Visited); | |||
1408 | std::reverse(MetadataArgs.begin(), MetadataArgs.end()); | |||
1409 | LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); | |||
1410 | ||||
1411 | // Add the linker options metadata flag. | |||
1412 | auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options"); | |||
1413 | for (auto *MD : LinkerOptionsMetadata) | |||
1414 | NMD->addOperand(MD); | |||
1415 | } | |||
1416 | ||||
1417 | void CodeGenModule::EmitDeferred() { | |||
1418 | // Emit code for any potentially referenced deferred decls. Since a | |||
1419 | // previously unused static decl may become used during the generation of code | |||
1420 | // for a static function, iterate until no changes are made. | |||
1421 | ||||
1422 | if (!DeferredVTables.empty()) { | |||
1423 | EmitDeferredVTables(); | |||
1424 | ||||
1425 | // Emitting a vtable doesn't directly cause more vtables to | |||
1426 | // become deferred, although it can cause functions to be | |||
1427 | // emitted that then need those vtables. | |||
1428 | assert(DeferredVTables.empty())(static_cast <bool> (DeferredVTables.empty()) ? void (0 ) : __assert_fail ("DeferredVTables.empty()", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 1428, __extension__ __PRETTY_FUNCTION__)); | |||
1429 | } | |||
1430 | ||||
1431 | // Stop if we're out of both deferred vtables and deferred declarations. | |||
1432 | if (DeferredDeclsToEmit.empty()) | |||
1433 | return; | |||
1434 | ||||
1435 | // Grab the list of decls to emit. If EmitGlobalDefinition schedules more | |||
1436 | // work, it will not interfere with this. | |||
1437 | std::vector<GlobalDecl> CurDeclsToEmit; | |||
1438 | CurDeclsToEmit.swap(DeferredDeclsToEmit); | |||
1439 | ||||
1440 | for (GlobalDecl &D : CurDeclsToEmit) { | |||
1441 | // We should call GetAddrOfGlobal with IsForDefinition set to true in order | |||
1442 | // to get GlobalValue with exactly the type we need, not something that | |||
1443 | // might had been created for another decl with the same mangled name but | |||
1444 | // different type. | |||
1445 | llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>( | |||
1446 | GetAddrOfGlobal(D, ForDefinition)); | |||
1447 | ||||
1448 | // In case of different address spaces, we may still get a cast, even with | |||
1449 | // IsForDefinition equal to true. Query mangled names table to get | |||
1450 | // GlobalValue. | |||
1451 | if (!GV) | |||
1452 | GV = GetGlobalValue(getMangledName(D)); | |||
1453 | ||||
1454 | // Make sure GetGlobalValue returned non-null. | |||
1455 | assert(GV)(static_cast <bool> (GV) ? void (0) : __assert_fail ("GV" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 1455, __extension__ __PRETTY_FUNCTION__)); | |||
1456 | ||||
1457 | // Check to see if we've already emitted this. This is necessary | |||
1458 | // for a couple of reasons: first, decls can end up in the | |||
1459 | // deferred-decls queue multiple times, and second, decls can end | |||
1460 | // up with definitions in unusual ways (e.g. by an extern inline | |||
1461 | // function acquiring a strong function redefinition). Just | |||
1462 | // ignore these cases. | |||
1463 | if (!GV->isDeclaration()) | |||
1464 | continue; | |||
1465 | ||||
1466 | // Otherwise, emit the definition and move on to the next one. | |||
1467 | EmitGlobalDefinition(D, GV); | |||
1468 | ||||
1469 | // If we found out that we need to emit more decls, do that recursively. | |||
1470 | // This has the advantage that the decls are emitted in a DFS and related | |||
1471 | // ones are close together, which is convenient for testing. | |||
1472 | if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { | |||
1473 | EmitDeferred(); | |||
1474 | assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty())(static_cast <bool> (DeferredVTables.empty() && DeferredDeclsToEmit.empty()) ? void (0) : __assert_fail ("DeferredVTables.empty() && DeferredDeclsToEmit.empty()" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 1474, __extension__ __PRETTY_FUNCTION__)); | |||
1475 | } | |||
1476 | } | |||
1477 | } | |||
1478 | ||||
1479 | void CodeGenModule::EmitVTablesOpportunistically() { | |||
1480 | // Try to emit external vtables as available_externally if they have emitted | |||
1481 | // all inlined virtual functions. It runs after EmitDeferred() and therefore | |||
1482 | // is not allowed to create new references to things that need to be emitted | |||
1483 | // lazily. Note that it also uses fact that we eagerly emitting RTTI. | |||
1484 | ||||
1485 | assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())(static_cast <bool> ((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables ()) && "Only emit opportunistic vtables with optimizations" ) ? void (0) : __assert_fail ("(OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) && \"Only emit opportunistic vtables with optimizations\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 1486, __extension__ __PRETTY_FUNCTION__)) | |||
1486 | && "Only emit opportunistic vtables with optimizations")(static_cast <bool> ((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables ()) && "Only emit opportunistic vtables with optimizations" ) ? void (0) : __assert_fail ("(OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) && \"Only emit opportunistic vtables with optimizations\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 1486, __extension__ __PRETTY_FUNCTION__)); | |||
1487 | ||||
1488 | for (const CXXRecordDecl *RD : OpportunisticVTables) { | |||
1489 | assert(getVTables().isVTableExternal(RD) &&(static_cast <bool> (getVTables().isVTableExternal(RD) && "This queue should only contain external vtables") ? void (0 ) : __assert_fail ("getVTables().isVTableExternal(RD) && \"This queue should only contain external vtables\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 1490, __extension__ __PRETTY_FUNCTION__)) | |||
1490 | "This queue should only contain external vtables")(static_cast <bool> (getVTables().isVTableExternal(RD) && "This queue should only contain external vtables") ? void (0 ) : __assert_fail ("getVTables().isVTableExternal(RD) && \"This queue should only contain external vtables\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 1490, __extension__ __PRETTY_FUNCTION__)); | |||
1491 | if (getCXXABI().canSpeculativelyEmitVTable(RD)) | |||
1492 | VTables.GenerateClassData(RD); | |||
1493 | } | |||
1494 | OpportunisticVTables.clear(); | |||
1495 | } | |||
1496 | ||||
1497 | void CodeGenModule::EmitGlobalAnnotations() { | |||
1498 | if (Annotations.empty()) | |||
1499 | return; | |||
1500 | ||||
1501 | // Create a new global variable for the ConstantStruct in the Module. | |||
1502 | llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( | |||
1503 | Annotations[0]->getType(), Annotations.size()), Annotations); | |||
1504 | auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, | |||
1505 | llvm::GlobalValue::AppendingLinkage, | |||
1506 | Array, "llvm.global.annotations"); | |||
1507 | gv->setSection(AnnotationSection); | |||
1508 | } | |||
1509 | ||||
1510 | llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { | |||
1511 | llvm::Constant *&AStr = AnnotationStrings[Str]; | |||
1512 | if (AStr) | |||
1513 | return AStr; | |||
1514 | ||||
1515 | // Not found yet, create a new global. | |||
1516 | llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); | |||
1517 | auto *gv = | |||
1518 | new llvm::GlobalVariable(getModule(), s->getType(), true, | |||
1519 | llvm::GlobalValue::PrivateLinkage, s, ".str"); | |||
1520 | gv->setSection(AnnotationSection); | |||
1521 | gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); | |||
1522 | AStr = gv; | |||
1523 | return gv; | |||
1524 | } | |||
1525 | ||||
1526 | llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { | |||
1527 | SourceManager &SM = getContext().getSourceManager(); | |||
1528 | PresumedLoc PLoc = SM.getPresumedLoc(Loc); | |||
1529 | if (PLoc.isValid()) | |||
1530 | return EmitAnnotationString(PLoc.getFilename()); | |||
1531 | return EmitAnnotationString(SM.getBufferName(Loc)); | |||
1532 | } | |||
1533 | ||||
1534 | llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { | |||
1535 | SourceManager &SM = getContext().getSourceManager(); | |||
1536 | PresumedLoc PLoc = SM.getPresumedLoc(L); | |||
1537 | unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : | |||
1538 | SM.getExpansionLineNumber(L); | |||
1539 | return llvm::ConstantInt::get(Int32Ty, LineNo); | |||
1540 | } | |||
1541 | ||||
1542 | llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, | |||
1543 | const AnnotateAttr *AA, | |||
1544 | SourceLocation L) { | |||
1545 | // Get the globals for file name, annotation, and the line number. | |||
1546 | llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), | |||
1547 | *UnitGV = EmitAnnotationUnit(L), | |||
1548 | *LineNoCst = EmitAnnotationLineNo(L); | |||
1549 | ||||
1550 | // Create the ConstantStruct for the global annotation. | |||
1551 | llvm::Constant *Fields[4] = { | |||
1552 | llvm::ConstantExpr::getBitCast(GV, Int8PtrTy), | |||
1553 | llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), | |||
1554 | llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), | |||
1555 | LineNoCst | |||
1556 | }; | |||
1557 | return llvm::ConstantStruct::getAnon(Fields); | |||
1558 | } | |||
1559 | ||||
1560 | void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, | |||
1561 | llvm::GlobalValue *GV) { | |||
1562 | assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute")(static_cast <bool> (D->hasAttr<AnnotateAttr>( ) && "no annotate attribute") ? void (0) : __assert_fail ("D->hasAttr<AnnotateAttr>() && \"no annotate attribute\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 1562, __extension__ __PRETTY_FUNCTION__)); | |||
1563 | // Get the struct elements for these annotations. | |||
1564 | for (const auto *I : D->specific_attrs<AnnotateAttr>()) | |||
1565 | Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); | |||
1566 | } | |||
1567 | ||||
1568 | bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind, | |||
1569 | llvm::Function *Fn, | |||
1570 | SourceLocation Loc) const { | |||
1571 | const auto &SanitizerBL = getContext().getSanitizerBlacklist(); | |||
1572 | // Blacklist by function name. | |||
1573 | if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName())) | |||
1574 | return true; | |||
1575 | // Blacklist by location. | |||
1576 | if (Loc.isValid()) | |||
1577 | return SanitizerBL.isBlacklistedLocation(Kind, Loc); | |||
1578 | // If location is unknown, this may be a compiler-generated function. Assume | |||
1579 | // it's located in the main file. | |||
1580 | auto &SM = Context.getSourceManager(); | |||
1581 | if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { | |||
1582 | return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName()); | |||
1583 | } | |||
1584 | return false; | |||
1585 | } | |||
1586 | ||||
1587 | bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV, | |||
1588 | SourceLocation Loc, QualType Ty, | |||
1589 | StringRef Category) const { | |||
1590 | // For now globals can be blacklisted only in ASan and KASan. | |||
1591 | const SanitizerMask EnabledAsanMask = LangOpts.Sanitize.Mask & | |||
1592 | (SanitizerKind::Address | SanitizerKind::KernelAddress | SanitizerKind::HWAddress); | |||
1593 | if (!EnabledAsanMask) | |||
1594 | return false; | |||
1595 | const auto &SanitizerBL = getContext().getSanitizerBlacklist(); | |||
1596 | if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category)) | |||
1597 | return true; | |||
1598 | if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category)) | |||
1599 | return true; | |||
1600 | // Check global type. | |||
1601 | if (!Ty.isNull()) { | |||
1602 | // Drill down the array types: if global variable of a fixed type is | |||
1603 | // blacklisted, we also don't instrument arrays of them. | |||
1604 | while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) | |||
1605 | Ty = AT->getElementType(); | |||
1606 | Ty = Ty.getCanonicalType().getUnqualifiedType(); | |||
1607 | // We allow to blacklist only record types (classes, structs etc.) | |||
1608 | if (Ty->isRecordType()) { | |||
1609 | std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); | |||
1610 | if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category)) | |||
1611 | return true; | |||
1612 | } | |||
1613 | } | |||
1614 | return false; | |||
1615 | } | |||
1616 | ||||
1617 | bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, | |||
1618 | StringRef Category) const { | |||
1619 | if (!LangOpts.XRayInstrument) | |||
1620 | return false; | |||
1621 | const auto &XRayFilter = getContext().getXRayFilter(); | |||
1622 | using ImbueAttr = XRayFunctionFilter::ImbueAttribute; | |||
1623 | auto Attr = XRayFunctionFilter::ImbueAttribute::NONE; | |||
1624 | if (Loc.isValid()) | |||
1625 | Attr = XRayFilter.shouldImbueLocation(Loc, Category); | |||
1626 | if (Attr == ImbueAttr::NONE) | |||
1627 | Attr = XRayFilter.shouldImbueFunction(Fn->getName()); | |||
1628 | switch (Attr) { | |||
1629 | case ImbueAttr::NONE: | |||
1630 | return false; | |||
1631 | case ImbueAttr::ALWAYS: | |||
1632 | Fn->addFnAttr("function-instrument", "xray-always"); | |||
1633 | break; | |||
1634 | case ImbueAttr::ALWAYS_ARG1: | |||
1635 | Fn->addFnAttr("function-instrument", "xray-always"); | |||
1636 | Fn->addFnAttr("xray-log-args", "1"); | |||
1637 | break; | |||
1638 | case ImbueAttr::NEVER: | |||
1639 | Fn->addFnAttr("function-instrument", "xray-never"); | |||
1640 | break; | |||
1641 | } | |||
1642 | return true; | |||
1643 | } | |||
1644 | ||||
1645 | bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { | |||
1646 | // Never defer when EmitAllDecls is specified. | |||
1647 | if (LangOpts.EmitAllDecls) | |||
1648 | return true; | |||
1649 | ||||
1650 | return getContext().DeclMustBeEmitted(Global); | |||
1651 | } | |||
1652 | ||||
1653 | bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { | |||
1654 | if (const auto *FD = dyn_cast<FunctionDecl>(Global)) | |||
1655 | if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) | |||
1656 | // Implicit template instantiations may change linkage if they are later | |||
1657 | // explicitly instantiated, so they should not be emitted eagerly. | |||
1658 | return false; | |||
1659 | if (const auto *VD = dyn_cast<VarDecl>(Global)) | |||
1660 | if (Context.getInlineVariableDefinitionKind(VD) == | |||
1661 | ASTContext::InlineVariableDefinitionKind::WeakUnknown) | |||
1662 | // A definition of an inline constexpr static data member may change | |||
1663 | // linkage later if it's redeclared outside the class. | |||
1664 | return false; | |||
1665 | // If OpenMP is enabled and threadprivates must be generated like TLS, delay | |||
1666 | // codegen for global variables, because they may be marked as threadprivate. | |||
1667 | if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && | |||
1668 | getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global)) | |||
1669 | return false; | |||
1670 | ||||
1671 | return true; | |||
1672 | } | |||
1673 | ||||
1674 | ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor( | |||
1675 | const CXXUuidofExpr* E) { | |||
1676 | // Sema has verified that IIDSource has a __declspec(uuid()), and that its | |||
1677 | // well-formed. | |||
1678 | StringRef Uuid = E->getUuidStr(); | |||
1679 | std::string Name = "_GUID_" + Uuid.lower(); | |||
1680 | std::replace(Name.begin(), Name.end(), '-', '_'); | |||
1681 | ||||
1682 | // The UUID descriptor should be pointer aligned. | |||
1683 | CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes); | |||
1684 | ||||
1685 | // Look for an existing global. | |||
1686 | if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) | |||
1687 | return ConstantAddress(GV, Alignment); | |||
1688 | ||||
1689 | llvm::Constant *Init = EmitUuidofInitializer(Uuid); | |||
1690 | assert(Init && "failed to initialize as constant")(static_cast <bool> (Init && "failed to initialize as constant" ) ? void (0) : __assert_fail ("Init && \"failed to initialize as constant\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 1690, __extension__ __PRETTY_FUNCTION__)); | |||
1691 | ||||
1692 | auto *GV = new llvm::GlobalVariable( | |||
1693 | getModule(), Init->getType(), | |||
1694 | /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); | |||
1695 | if (supportsCOMDAT()) | |||
1696 | GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); | |||
1697 | return ConstantAddress(GV, Alignment); | |||
1698 | } | |||
1699 | ||||
1700 | ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { | |||
1701 | const AliasAttr *AA = VD->getAttr<AliasAttr>(); | |||
1702 | assert(AA && "No alias?")(static_cast <bool> (AA && "No alias?") ? void ( 0) : __assert_fail ("AA && \"No alias?\"", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 1702, __extension__ __PRETTY_FUNCTION__)); | |||
1703 | ||||
1704 | CharUnits Alignment = getContext().getDeclAlign(VD); | |||
1705 | llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); | |||
1706 | ||||
1707 | // See if there is already something with the target's name in the module. | |||
1708 | llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); | |||
1709 | if (Entry) { | |||
1710 | unsigned AS = getContext().getTargetAddressSpace(VD->getType()); | |||
1711 | auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); | |||
1712 | return ConstantAddress(Ptr, Alignment); | |||
1713 | } | |||
1714 | ||||
1715 | llvm::Constant *Aliasee; | |||
1716 | if (isa<llvm::FunctionType>(DeclTy)) | |||
1717 | Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, | |||
1718 | GlobalDecl(cast<FunctionDecl>(VD)), | |||
1719 | /*ForVTable=*/false); | |||
1720 | else | |||
1721 | Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), | |||
1722 | llvm::PointerType::getUnqual(DeclTy), | |||
1723 | nullptr); | |||
1724 | ||||
1725 | auto *F = cast<llvm::GlobalValue>(Aliasee); | |||
1726 | F->setLinkage(llvm::Function::ExternalWeakLinkage); | |||
1727 | WeakRefReferences.insert(F); | |||
1728 | ||||
1729 | return ConstantAddress(Aliasee, Alignment); | |||
1730 | } | |||
1731 | ||||
1732 | void CodeGenModule::EmitGlobal(GlobalDecl GD) { | |||
1733 | const auto *Global = cast<ValueDecl>(GD.getDecl()); | |||
1734 | ||||
1735 | // Weak references don't produce any output by themselves. | |||
1736 | if (Global->hasAttr<WeakRefAttr>()) | |||
1737 | return; | |||
1738 | ||||
1739 | // If this is an alias definition (which otherwise looks like a declaration) | |||
1740 | // emit it now. | |||
1741 | if (Global->hasAttr<AliasAttr>()) | |||
1742 | return EmitAliasDefinition(GD); | |||
1743 | ||||
1744 | // IFunc like an alias whose value is resolved at runtime by calling resolver. | |||
1745 | if (Global->hasAttr<IFuncAttr>()) | |||
1746 | return emitIFuncDefinition(GD); | |||
1747 | ||||
1748 | // If this is CUDA, be selective about which declarations we emit. | |||
1749 | if (LangOpts.CUDA) { | |||
1750 | if (LangOpts.CUDAIsDevice) { | |||
1751 | if (!Global->hasAttr<CUDADeviceAttr>() && | |||
1752 | !Global->hasAttr<CUDAGlobalAttr>() && | |||
1753 | !Global->hasAttr<CUDAConstantAttr>() && | |||
1754 | !Global->hasAttr<CUDASharedAttr>()) | |||
1755 | return; | |||
1756 | } else { | |||
1757 | // We need to emit host-side 'shadows' for all global | |||
1758 | // device-side variables because the CUDA runtime needs their | |||
1759 | // size and host-side address in order to provide access to | |||
1760 | // their device-side incarnations. | |||
1761 | ||||
1762 | // So device-only functions are the only things we skip. | |||
1763 | if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() && | |||
1764 | Global->hasAttr<CUDADeviceAttr>()) | |||
1765 | return; | |||
1766 | ||||
1767 | assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&(static_cast <bool> ((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && "Expected Variable or Function" ) ? void (0) : __assert_fail ("(isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && \"Expected Variable or Function\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 1768, __extension__ __PRETTY_FUNCTION__)) | |||
1768 | "Expected Variable or Function")(static_cast <bool> ((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && "Expected Variable or Function" ) ? void (0) : __assert_fail ("(isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && \"Expected Variable or Function\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 1768, __extension__ __PRETTY_FUNCTION__)); | |||
1769 | } | |||
1770 | } | |||
1771 | ||||
1772 | if (LangOpts.OpenMP) { | |||
1773 | // If this is OpenMP device, check if it is legal to emit this global | |||
1774 | // normally. | |||
1775 | if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD)) | |||
1776 | return; | |||
1777 | if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) { | |||
1778 | if (MustBeEmitted(Global)) | |||
1779 | EmitOMPDeclareReduction(DRD); | |||
1780 | return; | |||
1781 | } | |||
1782 | } | |||
1783 | ||||
1784 | // Ignore declarations, they will be emitted on their first use. | |||
1785 | if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { | |||
1786 | // Forward declarations are emitted lazily on first use. | |||
1787 | if (!FD->doesThisDeclarationHaveABody()) { | |||
1788 | if (!FD->doesDeclarationForceExternallyVisibleDefinition()) | |||
1789 | return; | |||
1790 | ||||
1791 | StringRef MangledName = getMangledName(GD); | |||
1792 | ||||
1793 | // Compute the function info and LLVM type. | |||
1794 | const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); | |||
1795 | llvm::Type *Ty = getTypes().GetFunctionType(FI); | |||
1796 | ||||
1797 | GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, | |||
1798 | /*DontDefer=*/false); | |||
1799 | return; | |||
1800 | } | |||
1801 | } else { | |||
1802 | const auto *VD = cast<VarDecl>(Global); | |||
1803 | assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.")(static_cast <bool> (VD->isFileVarDecl() && "Cannot emit local var decl as global." ) ? void (0) : __assert_fail ("VD->isFileVarDecl() && \"Cannot emit local var decl as global.\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 1803, __extension__ __PRETTY_FUNCTION__)); | |||
1804 | // We need to emit device-side global CUDA variables even if a | |||
1805 | // variable does not have a definition -- we still need to define | |||
1806 | // host-side shadow for it. | |||
1807 | bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice && | |||
1808 | !VD->hasDefinition() && | |||
1809 | (VD->hasAttr<CUDAConstantAttr>() || | |||
1810 | VD->hasAttr<CUDADeviceAttr>()); | |||
1811 | if (!MustEmitForCuda && | |||
1812 | VD->isThisDeclarationADefinition() != VarDecl::Definition && | |||
1813 | !Context.isMSStaticDataMemberInlineDefinition(VD)) { | |||
1814 | // If this declaration may have caused an inline variable definition to | |||
1815 | // change linkage, make sure that it's emitted. | |||
1816 | if (Context.getInlineVariableDefinitionKind(VD) == | |||
1817 | ASTContext::InlineVariableDefinitionKind::Strong) | |||
1818 | GetAddrOfGlobalVar(VD); | |||
1819 | return; | |||
1820 | } | |||
1821 | } | |||
1822 | ||||
1823 | // Defer code generation to first use when possible, e.g. if this is an inline | |||
1824 | // function. If the global must always be emitted, do it eagerly if possible | |||
1825 | // to benefit from cache locality. | |||
1826 | if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { | |||
1827 | // Emit the definition if it can't be deferred. | |||
1828 | EmitGlobalDefinition(GD); | |||
1829 | return; | |||
1830 | } | |||
1831 | ||||
1832 | // If we're deferring emission of a C++ variable with an | |||
1833 | // initializer, remember the order in which it appeared in the file. | |||
1834 | if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && | |||
1835 | cast<VarDecl>(Global)->hasInit()) { | |||
1836 | DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); | |||
1837 | CXXGlobalInits.push_back(nullptr); | |||
1838 | } | |||
1839 | ||||
1840 | StringRef MangledName = getMangledName(GD); | |||
1841 | if (GetGlobalValue(MangledName) != nullptr) { | |||
1842 | // The value has already been used and should therefore be emitted. | |||
1843 | addDeferredDeclToEmit(GD); | |||
1844 | } else if (MustBeEmitted(Global)) { | |||
1845 | // The value must be emitted, but cannot be emitted eagerly. | |||
1846 | assert(!MayBeEmittedEagerly(Global))(static_cast <bool> (!MayBeEmittedEagerly(Global)) ? void (0) : __assert_fail ("!MayBeEmittedEagerly(Global)", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 1846, __extension__ __PRETTY_FUNCTION__)); | |||
1847 | addDeferredDeclToEmit(GD); | |||
1848 | } else { | |||
1849 | // Otherwise, remember that we saw a deferred decl with this name. The | |||
1850 | // first use of the mangled name will cause it to move into | |||
1851 | // DeferredDeclsToEmit. | |||
1852 | DeferredDecls[MangledName] = GD; | |||
1853 | } | |||
1854 | } | |||
1855 | ||||
1856 | // Check if T is a class type with a destructor that's not dllimport. | |||
1857 | static bool HasNonDllImportDtor(QualType T) { | |||
1858 | if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>()) | |||
1859 | if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) | |||
1860 | if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>()) | |||
1861 | return true; | |||
1862 | ||||
1863 | return false; | |||
1864 | } | |||
1865 | ||||
1866 | namespace { | |||
1867 | struct FunctionIsDirectlyRecursive : | |||
1868 | public RecursiveASTVisitor<FunctionIsDirectlyRecursive> { | |||
1869 | const StringRef Name; | |||
1870 | const Builtin::Context &BI; | |||
1871 | bool Result; | |||
1872 | FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) : | |||
1873 | Name(N), BI(C), Result(false) { | |||
1874 | } | |||
1875 | typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base; | |||
1876 | ||||
1877 | bool TraverseCallExpr(CallExpr *E) { | |||
1878 | const FunctionDecl *FD = E->getDirectCallee(); | |||
1879 | if (!FD) | |||
1880 | return true; | |||
1881 | AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); | |||
1882 | if (Attr && Name == Attr->getLabel()) { | |||
1883 | Result = true; | |||
1884 | return false; | |||
1885 | } | |||
1886 | unsigned BuiltinID = FD->getBuiltinID(); | |||
1887 | if (!BuiltinID || !BI.isLibFunction(BuiltinID)) | |||
1888 | return true; | |||
1889 | StringRef BuiltinName = BI.getName(BuiltinID); | |||
1890 | if (BuiltinName.startswith("__builtin_") && | |||
1891 | Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { | |||
1892 | Result = true; | |||
1893 | return false; | |||
1894 | } | |||
1895 | return true; | |||
1896 | } | |||
1897 | }; | |||
1898 | ||||
1899 | // Make sure we're not referencing non-imported vars or functions. | |||
1900 | struct DLLImportFunctionVisitor | |||
1901 | : public RecursiveASTVisitor<DLLImportFunctionVisitor> { | |||
1902 | bool SafeToInline = true; | |||
1903 | ||||
1904 | bool shouldVisitImplicitCode() const { return true; } | |||
1905 | ||||
1906 | bool VisitVarDecl(VarDecl *VD) { | |||
1907 | if (VD->getTLSKind()) { | |||
1908 | // A thread-local variable cannot be imported. | |||
1909 | SafeToInline = false; | |||
1910 | return SafeToInline; | |||
1911 | } | |||
1912 | ||||
1913 | // A variable definition might imply a destructor call. | |||
1914 | if (VD->isThisDeclarationADefinition()) | |||
1915 | SafeToInline = !HasNonDllImportDtor(VD->getType()); | |||
1916 | ||||
1917 | return SafeToInline; | |||
1918 | } | |||
1919 | ||||
1920 | bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { | |||
1921 | if (const auto *D = E->getTemporary()->getDestructor()) | |||
1922 | SafeToInline = D->hasAttr<DLLImportAttr>(); | |||
1923 | return SafeToInline; | |||
1924 | } | |||
1925 | ||||
1926 | bool VisitDeclRefExpr(DeclRefExpr *E) { | |||
1927 | ValueDecl *VD = E->getDecl(); | |||
1928 | if (isa<FunctionDecl>(VD)) | |||
1929 | SafeToInline = VD->hasAttr<DLLImportAttr>(); | |||
1930 | else if (VarDecl *V = dyn_cast<VarDecl>(VD)) | |||
1931 | SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); | |||
1932 | return SafeToInline; | |||
1933 | } | |||
1934 | ||||
1935 | bool VisitCXXConstructExpr(CXXConstructExpr *E) { | |||
1936 | SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>(); | |||
1937 | return SafeToInline; | |||
1938 | } | |||
1939 | ||||
1940 | bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { | |||
1941 | CXXMethodDecl *M = E->getMethodDecl(); | |||
1942 | if (!M) { | |||
1943 | // Call through a pointer to member function. This is safe to inline. | |||
1944 | SafeToInline = true; | |||
1945 | } else { | |||
1946 | SafeToInline = M->hasAttr<DLLImportAttr>(); | |||
1947 | } | |||
1948 | return SafeToInline; | |||
1949 | } | |||
1950 | ||||
1951 | bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { | |||
1952 | SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); | |||
1953 | return SafeToInline; | |||
1954 | } | |||
1955 | ||||
1956 | bool VisitCXXNewExpr(CXXNewExpr *E) { | |||
1957 | SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); | |||
1958 | return SafeToInline; | |||
1959 | } | |||
1960 | }; | |||
1961 | } | |||
1962 | ||||
1963 | // isTriviallyRecursive - Check if this function calls another | |||
1964 | // decl that, because of the asm attribute or the other decl being a builtin, | |||
1965 | // ends up pointing to itself. | |||
1966 | bool | |||
1967 | CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { | |||
1968 | StringRef Name; | |||
1969 | if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { | |||
1970 | // asm labels are a special kind of mangling we have to support. | |||
1971 | AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); | |||
1972 | if (!Attr) | |||
1973 | return false; | |||
1974 | Name = Attr->getLabel(); | |||
1975 | } else { | |||
1976 | Name = FD->getName(); | |||
1977 | } | |||
1978 | ||||
1979 | FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); | |||
1980 | Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD)); | |||
1981 | return Walker.Result; | |||
1982 | } | |||
1983 | ||||
1984 | bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) { | |||
1985 | if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) | |||
1986 | return true; | |||
1987 | const auto *F = cast<FunctionDecl>(GD.getDecl()); | |||
1988 | if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) | |||
1989 | return false; | |||
1990 | ||||
1991 | if (F->hasAttr<DLLImportAttr>()) { | |||
1992 | // Check whether it would be safe to inline this dllimport function. | |||
1993 | DLLImportFunctionVisitor Visitor; | |||
1994 | Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); | |||
1995 | if (!Visitor.SafeToInline) | |||
1996 | return false; | |||
1997 | ||||
1998 | if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) { | |||
1999 | // Implicit destructor invocations aren't captured in the AST, so the | |||
2000 | // check above can't see them. Check for them manually here. | |||
2001 | for (const Decl *Member : Dtor->getParent()->decls()) | |||
2002 | if (isa<FieldDecl>(Member)) | |||
2003 | if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType())) | |||
2004 | return false; | |||
2005 | for (const CXXBaseSpecifier &B : Dtor->getParent()->bases()) | |||
2006 | if (HasNonDllImportDtor(B.getType())) | |||
2007 | return false; | |||
2008 | } | |||
2009 | } | |||
2010 | ||||
2011 | // PR9614. Avoid cases where the source code is lying to us. An available | |||
2012 | // externally function should have an equivalent function somewhere else, | |||
2013 | // but a function that calls itself is clearly not equivalent to the real | |||
2014 | // implementation. | |||
2015 | // This happens in glibc's btowc and in some configure checks. | |||
2016 | return !isTriviallyRecursive(F); | |||
2017 | } | |||
2018 | ||||
2019 | bool CodeGenModule::shouldOpportunisticallyEmitVTables() { | |||
2020 | return CodeGenOpts.OptimizationLevel > 0; | |||
2021 | } | |||
2022 | ||||
2023 | void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { | |||
2024 | const auto *D = cast<ValueDecl>(GD.getDecl()); | |||
2025 | ||||
2026 | PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), | |||
2027 | Context.getSourceManager(), | |||
2028 | "Generating code for declaration"); | |||
2029 | ||||
2030 | if (isa<FunctionDecl>(D)) { | |||
2031 | // At -O0, don't generate IR for functions with available_externally | |||
2032 | // linkage. | |||
2033 | if (!shouldEmitFunction(GD)) | |||
2034 | return; | |||
2035 | ||||
2036 | if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { | |||
2037 | // Make sure to emit the definition(s) before we emit the thunks. | |||
2038 | // This is necessary for the generation of certain thunks. | |||
2039 | if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method)) | |||
2040 | ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType())); | |||
2041 | else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method)) | |||
2042 | ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType())); | |||
2043 | else | |||
2044 | EmitGlobalFunctionDefinition(GD, GV); | |||
2045 | ||||
2046 | if (Method->isVirtual()) | |||
2047 | getVTables().EmitThunks(GD); | |||
2048 | ||||
2049 | return; | |||
2050 | } | |||
2051 | ||||
2052 | return EmitGlobalFunctionDefinition(GD, GV); | |||
2053 | } | |||
2054 | ||||
2055 | if (const auto *VD = dyn_cast<VarDecl>(D)) | |||
2056 | return EmitGlobalVarDefinition(VD, !VD->hasDefinition()); | |||
2057 | ||||
2058 | llvm_unreachable("Invalid argument to EmitGlobalDefinition()")::llvm::llvm_unreachable_internal("Invalid argument to EmitGlobalDefinition()" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 2058); | |||
2059 | } | |||
2060 | ||||
2061 | static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, | |||
2062 | llvm::Function *NewFn); | |||
2063 | ||||
2064 | /// GetOrCreateLLVMFunction - If the specified mangled name is not in the | |||
2065 | /// module, create and return an llvm Function with the specified type. If there | |||
2066 | /// is something in the module with the specified name, return it potentially | |||
2067 | /// bitcasted to the right type. | |||
2068 | /// | |||
2069 | /// If D is non-null, it specifies a decl that correspond to this. This is used | |||
2070 | /// to set the attributes on the function when it is first created. | |||
2071 | llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction( | |||
2072 | StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable, | |||
2073 | bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs, | |||
2074 | ForDefinition_t IsForDefinition) { | |||
2075 | const Decl *D = GD.getDecl(); | |||
2076 | ||||
2077 | // Lookup the entry, lazily creating it if necessary. | |||
2078 | llvm::GlobalValue *Entry = GetGlobalValue(MangledName); | |||
2079 | if (Entry) { | |||
2080 | if (WeakRefReferences.erase(Entry)) { | |||
2081 | const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); | |||
2082 | if (FD && !FD->hasAttr<WeakAttr>()) | |||
2083 | Entry->setLinkage(llvm::Function::ExternalLinkage); | |||
2084 | } | |||
2085 | ||||
2086 | // Handle dropped DLL attributes. | |||
2087 | if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) | |||
2088 | Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); | |||
2089 | ||||
2090 | // If there are two attempts to define the same mangled name, issue an | |||
2091 | // error. | |||
2092 | if (IsForDefinition && !Entry->isDeclaration()) { | |||
2093 | GlobalDecl OtherGD; | |||
2094 | // Check that GD is not yet in DiagnosedConflictingDefinitions is required | |||
2095 | // to make sure that we issue an error only once. | |||
2096 | if (lookupRepresentativeDecl(MangledName, OtherGD) && | |||
2097 | (GD.getCanonicalDecl().getDecl() != | |||
2098 | OtherGD.getCanonicalDecl().getDecl()) && | |||
2099 | DiagnosedConflictingDefinitions.insert(GD).second) { | |||
2100 | getDiags().Report(D->getLocation(), | |||
2101 | diag::err_duplicate_mangled_name); | |||
2102 | getDiags().Report(OtherGD.getDecl()->getLocation(), | |||
2103 | diag::note_previous_definition); | |||
2104 | } | |||
2105 | } | |||
2106 | ||||
2107 | if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && | |||
2108 | (Entry->getType()->getElementType() == Ty)) { | |||
2109 | return Entry; | |||
2110 | } | |||
2111 | ||||
2112 | // Make sure the result is of the correct type. | |||
2113 | // (If function is requested for a definition, we always need to create a new | |||
2114 | // function, not just return a bitcast.) | |||
2115 | if (!IsForDefinition) | |||
2116 | return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); | |||
2117 | } | |||
2118 | ||||
2119 | // This function doesn't have a complete type (for example, the return | |||
2120 | // type is an incomplete struct). Use a fake type instead, and make | |||
2121 | // sure not to try to set attributes. | |||
2122 | bool IsIncompleteFunction = false; | |||
2123 | ||||
2124 | llvm::FunctionType *FTy; | |||
2125 | if (isa<llvm::FunctionType>(Ty)) { | |||
2126 | FTy = cast<llvm::FunctionType>(Ty); | |||
2127 | } else { | |||
2128 | FTy = llvm::FunctionType::get(VoidTy, false); | |||
2129 | IsIncompleteFunction = true; | |||
2130 | } | |||
2131 | ||||
2132 | llvm::Function *F = | |||
2133 | llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, | |||
2134 | Entry ? StringRef() : MangledName, &getModule()); | |||
2135 | ||||
2136 | // If we already created a function with the same mangled name (but different | |||
2137 | // type) before, take its name and add it to the list of functions to be | |||
2138 | // replaced with F at the end of CodeGen. | |||
2139 | // | |||
2140 | // This happens if there is a prototype for a function (e.g. "int f()") and | |||
2141 | // then a definition of a different type (e.g. "int f(int x)"). | |||
2142 | if (Entry) { | |||
2143 | F->takeName(Entry); | |||
2144 | ||||
2145 | // This might be an implementation of a function without a prototype, in | |||
2146 | // which case, try to do special replacement of calls which match the new | |||
2147 | // prototype. The really key thing here is that we also potentially drop | |||
2148 | // arguments from the call site so as to make a direct call, which makes the | |||
2149 | // inliner happier and suppresses a number of optimizer warnings (!) about | |||
2150 | // dropping arguments. | |||
2151 | if (!Entry->use_empty()) { | |||
2152 | ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); | |||
2153 | Entry->removeDeadConstantUsers(); | |||
2154 | } | |||
2155 | ||||
2156 | llvm::Constant *BC = llvm::ConstantExpr::getBitCast( | |||
2157 | F, Entry->getType()->getElementType()->getPointerTo()); | |||
2158 | addGlobalValReplacement(Entry, BC); | |||
2159 | } | |||
2160 | ||||
2161 | assert(F->getName() == MangledName && "name was uniqued!")(static_cast <bool> (F->getName() == MangledName && "name was uniqued!") ? void (0) : __assert_fail ("F->getName() == MangledName && \"name was uniqued!\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 2161, __extension__ __PRETTY_FUNCTION__)); | |||
2162 | if (D) | |||
2163 | SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk, | |||
2164 | IsForDefinition); | |||
2165 | if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) { | |||
2166 | llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex); | |||
2167 | F->addAttributes(llvm::AttributeList::FunctionIndex, B); | |||
2168 | } | |||
2169 | ||||
2170 | if (!DontDefer) { | |||
2171 | // All MSVC dtors other than the base dtor are linkonce_odr and delegate to | |||
2172 | // each other bottoming out with the base dtor. Therefore we emit non-base | |||
2173 | // dtors on usage, even if there is no dtor definition in the TU. | |||
2174 | if (D && isa<CXXDestructorDecl>(D) && | |||
2175 | getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), | |||
2176 | GD.getDtorType())) | |||
2177 | addDeferredDeclToEmit(GD); | |||
2178 | ||||
2179 | // This is the first use or definition of a mangled name. If there is a | |||
2180 | // deferred decl with this name, remember that we need to emit it at the end | |||
2181 | // of the file. | |||
2182 | auto DDI = DeferredDecls.find(MangledName); | |||
2183 | if (DDI != DeferredDecls.end()) { | |||
2184 | // Move the potentially referenced deferred decl to the | |||
2185 | // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we | |||
2186 | // don't need it anymore). | |||
2187 | addDeferredDeclToEmit(DDI->second); | |||
2188 | DeferredDecls.erase(DDI); | |||
2189 | ||||
2190 | // Otherwise, there are cases we have to worry about where we're | |||
2191 | // using a declaration for which we must emit a definition but where | |||
2192 | // we might not find a top-level definition: | |||
2193 | // - member functions defined inline in their classes | |||
2194 | // - friend functions defined inline in some class | |||
2195 | // - special member functions with implicit definitions | |||
2196 | // If we ever change our AST traversal to walk into class methods, | |||
2197 | // this will be unnecessary. | |||
2198 | // | |||
2199 | // We also don't emit a definition for a function if it's going to be an | |||
2200 | // entry in a vtable, unless it's already marked as used. | |||
2201 | } else if (getLangOpts().CPlusPlus && D) { | |||
2202 | // Look for a declaration that's lexically in a record. | |||
2203 | for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; | |||
2204 | FD = FD->getPreviousDecl()) { | |||
2205 | if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { | |||
2206 | if (FD->doesThisDeclarationHaveABody()) { | |||
2207 | addDeferredDeclToEmit(GD.getWithDecl(FD)); | |||
2208 | break; | |||
2209 | } | |||
2210 | } | |||
2211 | } | |||
2212 | } | |||
2213 | } | |||
2214 | ||||
2215 | // Make sure the result is of the requested type. | |||
2216 | if (!IsIncompleteFunction) { | |||
2217 | assert(F->getType()->getElementType() == Ty)(static_cast <bool> (F->getType()->getElementType () == Ty) ? void (0) : __assert_fail ("F->getType()->getElementType() == Ty" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 2217, __extension__ __PRETTY_FUNCTION__)); | |||
2218 | return F; | |||
2219 | } | |||
2220 | ||||
2221 | llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); | |||
2222 | return llvm::ConstantExpr::getBitCast(F, PTy); | |||
2223 | } | |||
2224 | ||||
2225 | /// GetAddrOfFunction - Return the address of the given function. If Ty is | |||
2226 | /// non-null, then this function will use the specified type if it has to | |||
2227 | /// create it (this occurs when we see a definition of the function). | |||
2228 | llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, | |||
2229 | llvm::Type *Ty, | |||
2230 | bool ForVTable, | |||
2231 | bool DontDefer, | |||
2232 | ForDefinition_t IsForDefinition) { | |||
2233 | // If there was no specific requested type, just convert it now. | |||
2234 | if (!Ty) { | |||
2235 | const auto *FD = cast<FunctionDecl>(GD.getDecl()); | |||
2236 | auto CanonTy = Context.getCanonicalType(FD->getType()); | |||
2237 | Ty = getTypes().ConvertFunctionType(CanonTy, FD); | |||
2238 | } | |||
2239 | ||||
2240 | StringRef MangledName = getMangledName(GD); | |||
2241 | return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, | |||
2242 | /*IsThunk=*/false, llvm::AttributeList(), | |||
2243 | IsForDefinition); | |||
2244 | } | |||
2245 | ||||
2246 | static const FunctionDecl * | |||
2247 | GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) { | |||
2248 | TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl(); | |||
2249 | DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); | |||
2250 | ||||
2251 | IdentifierInfo &CII = C.Idents.get(Name); | |||
2252 | for (const auto &Result : DC->lookup(&CII)) | |||
2253 | if (const auto FD = dyn_cast<FunctionDecl>(Result)) | |||
2254 | return FD; | |||
2255 | ||||
2256 | if (!C.getLangOpts().CPlusPlus) | |||
2257 | return nullptr; | |||
2258 | ||||
2259 | // Demangle the premangled name from getTerminateFn() | |||
2260 | IdentifierInfo &CXXII = | |||
2261 | (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ") | |||
2262 | ? C.Idents.get("terminate") | |||
2263 | : C.Idents.get(Name); | |||
2264 | ||||
2265 | for (const auto &N : {"__cxxabiv1", "std"}) { | |||
2266 | IdentifierInfo &NS = C.Idents.get(N); | |||
2267 | for (const auto &Result : DC->lookup(&NS)) { | |||
2268 | NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result); | |||
2269 | if (auto LSD = dyn_cast<LinkageSpecDecl>(Result)) | |||
2270 | for (const auto &Result : LSD->lookup(&NS)) | |||
2271 | if ((ND = dyn_cast<NamespaceDecl>(Result))) | |||
2272 | break; | |||
2273 | ||||
2274 | if (ND) | |||
2275 | for (const auto &Result : ND->lookup(&CXXII)) | |||
2276 | if (const auto *FD = dyn_cast<FunctionDecl>(Result)) | |||
2277 | return FD; | |||
2278 | } | |||
2279 | } | |||
2280 | ||||
2281 | return nullptr; | |||
2282 | } | |||
2283 | ||||
2284 | /// CreateRuntimeFunction - Create a new runtime function with the specified | |||
2285 | /// type and name. | |||
2286 | llvm::Constant * | |||
2287 | CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name, | |||
2288 | llvm::AttributeList ExtraAttrs, | |||
2289 | bool Local) { | |||
2290 | llvm::Constant *C = | |||
2291 | GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, | |||
2292 | /*DontDefer=*/false, /*IsThunk=*/false, | |||
2293 | ExtraAttrs); | |||
2294 | ||||
2295 | if (auto *F = dyn_cast<llvm::Function>(C)) { | |||
2296 | if (F->empty()) { | |||
2297 | F->setCallingConv(getRuntimeCC()); | |||
2298 | ||||
2299 | if (!Local && getTriple().isOSBinFormatCOFF() && | |||
2300 | !getCodeGenOpts().LTOVisibilityPublicStd && | |||
2301 | !getTriple().isWindowsGNUEnvironment()) { | |||
2302 | const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name); | |||
2303 | if (!FD || FD->hasAttr<DLLImportAttr>()) { | |||
2304 | F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); | |||
2305 | F->setLinkage(llvm::GlobalValue::ExternalLinkage); | |||
2306 | } | |||
2307 | } | |||
2308 | } | |||
2309 | } | |||
2310 | ||||
2311 | return C; | |||
2312 | } | |||
2313 | ||||
2314 | /// CreateBuiltinFunction - Create a new builtin function with the specified | |||
2315 | /// type and name. | |||
2316 | llvm::Constant * | |||
2317 | CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name, | |||
2318 | llvm::AttributeList ExtraAttrs) { | |||
2319 | llvm::Constant *C = | |||
2320 | GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, | |||
2321 | /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs); | |||
2322 | if (auto *F = dyn_cast<llvm::Function>(C)) | |||
2323 | if (F->empty()) | |||
2324 | F->setCallingConv(getBuiltinCC()); | |||
2325 | return C; | |||
2326 | } | |||
2327 | ||||
2328 | /// isTypeConstant - Determine whether an object of this type can be emitted | |||
2329 | /// as a constant. | |||
2330 | /// | |||
2331 | /// If ExcludeCtor is true, the duration when the object's constructor runs | |||
2332 | /// will not be considered. The caller will need to verify that the object is | |||
2333 | /// not written to during its construction. | |||
2334 | bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { | |||
2335 | if (!Ty.isConstant(Context) && !Ty->isReferenceType()) | |||
2336 | return false; | |||
2337 | ||||
2338 | if (Context.getLangOpts().CPlusPlus) { | |||
2339 | if (const CXXRecordDecl *Record | |||
2340 | = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) | |||
2341 | return ExcludeCtor && !Record->hasMutableFields() && | |||
2342 | Record->hasTrivialDestructor(); | |||
2343 | } | |||
2344 | ||||
2345 | return true; | |||
2346 | } | |||
2347 | ||||
2348 | /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, | |||
2349 | /// create and return an llvm GlobalVariable with the specified type. If there | |||
2350 | /// is something in the module with the specified name, return it potentially | |||
2351 | /// bitcasted to the right type. | |||
2352 | /// | |||
2353 | /// If D is non-null, it specifies a decl that correspond to this. This is used | |||
2354 | /// to set the attributes on the global when it is first created. | |||
2355 | /// | |||
2356 | /// If IsForDefinition is true, it is guranteed that an actual global with | |||
2357 | /// type Ty will be returned, not conversion of a variable with the same | |||
2358 | /// mangled name but some other type. | |||
2359 | llvm::Constant * | |||
2360 | CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, | |||
2361 | llvm::PointerType *Ty, | |||
2362 | const VarDecl *D, | |||
2363 | ForDefinition_t IsForDefinition) { | |||
2364 | // Lookup the entry, lazily creating it if necessary. | |||
2365 | llvm::GlobalValue *Entry = GetGlobalValue(MangledName); | |||
2366 | if (Entry) { | |||
2367 | if (WeakRefReferences.erase(Entry)) { | |||
2368 | if (D && !D->hasAttr<WeakAttr>()) | |||
2369 | Entry->setLinkage(llvm::Function::ExternalLinkage); | |||
2370 | } | |||
2371 | ||||
2372 | // Handle dropped DLL attributes. | |||
2373 | if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) | |||
2374 | Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); | |||
2375 | ||||
2376 | if (Entry->getType() == Ty) | |||
2377 | return Entry; | |||
2378 | ||||
2379 | // If there are two attempts to define the same mangled name, issue an | |||
2380 | // error. | |||
2381 | if (IsForDefinition && !Entry->isDeclaration()) { | |||
2382 | GlobalDecl OtherGD; | |||
2383 | const VarDecl *OtherD; | |||
2384 | ||||
2385 | // Check that D is not yet in DiagnosedConflictingDefinitions is required | |||
2386 | // to make sure that we issue an error only once. | |||
2387 | if (D && lookupRepresentativeDecl(MangledName, OtherGD) && | |||
2388 | (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) && | |||
2389 | (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) && | |||
2390 | OtherD->hasInit() && | |||
2391 | DiagnosedConflictingDefinitions.insert(D).second) { | |||
2392 | getDiags().Report(D->getLocation(), | |||
2393 | diag::err_duplicate_mangled_name); | |||
2394 | getDiags().Report(OtherGD.getDecl()->getLocation(), | |||
2395 | diag::note_previous_definition); | |||
2396 | } | |||
2397 | } | |||
2398 | ||||
2399 | // Make sure the result is of the correct type. | |||
2400 | if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace()) | |||
2401 | return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty); | |||
2402 | ||||
2403 | // (If global is requested for a definition, we always need to create a new | |||
2404 | // global, not just return a bitcast.) | |||
2405 | if (!IsForDefinition) | |||
2406 | return llvm::ConstantExpr::getBitCast(Entry, Ty); | |||
2407 | } | |||
2408 | ||||
2409 | auto AddrSpace = GetGlobalVarAddressSpace(D); | |||
2410 | auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace); | |||
2411 | ||||
2412 | auto *GV = new llvm::GlobalVariable( | |||
2413 | getModule(), Ty->getElementType(), false, | |||
2414 | llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr, | |||
2415 | llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace); | |||
2416 | ||||
2417 | // If we already created a global with the same mangled name (but different | |||
2418 | // type) before, take its name and remove it from its parent. | |||
2419 | if (Entry) { | |||
2420 | GV->takeName(Entry); | |||
2421 | ||||
2422 | if (!Entry->use_empty()) { | |||
2423 | llvm::Constant *NewPtrForOldDecl = | |||
2424 | llvm::ConstantExpr::getBitCast(GV, Entry->getType()); | |||
2425 | Entry->replaceAllUsesWith(NewPtrForOldDecl); | |||
2426 | } | |||
2427 | ||||
2428 | Entry->eraseFromParent(); | |||
2429 | } | |||
2430 | ||||
2431 | // This is the first use or definition of a mangled name. If there is a | |||
2432 | // deferred decl with this name, remember that we need to emit it at the end | |||
2433 | // of the file. | |||
2434 | auto DDI = DeferredDecls.find(MangledName); | |||
2435 | if (DDI != DeferredDecls.end()) { | |||
2436 | // Move the potentially referenced deferred decl to the DeferredDeclsToEmit | |||
2437 | // list, and remove it from DeferredDecls (since we don't need it anymore). | |||
2438 | addDeferredDeclToEmit(DDI->second); | |||
2439 | DeferredDecls.erase(DDI); | |||
2440 | } | |||
2441 | ||||
2442 | // Handle things which are present even on external declarations. | |||
2443 | if (D) { | |||
2444 | // FIXME: This code is overly simple and should be merged with other global | |||
2445 | // handling. | |||
2446 | GV->setConstant(isTypeConstant(D->getType(), false)); | |||
2447 | ||||
2448 | GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); | |||
2449 | ||||
2450 | setLinkageForGV(GV, D); | |||
2451 | setGlobalVisibility(GV, D, NotForDefinition); | |||
2452 | ||||
2453 | if (D->getTLSKind()) { | |||
2454 | if (D->getTLSKind() == VarDecl::TLS_Dynamic) | |||
2455 | CXXThreadLocals.push_back(D); | |||
2456 | setTLSMode(GV, *D); | |||
2457 | } | |||
2458 | ||||
2459 | // If required by the ABI, treat declarations of static data members with | |||
2460 | // inline initializers as definitions. | |||
2461 | if (getContext().isMSStaticDataMemberInlineDefinition(D)) { | |||
2462 | EmitGlobalVarDefinition(D); | |||
2463 | } | |||
2464 | ||||
2465 | // Emit section information for extern variables. | |||
2466 | if (D->hasExternalStorage()) { | |||
2467 | if (const SectionAttr *SA = D->getAttr<SectionAttr>()) | |||
2468 | GV->setSection(SA->getName()); | |||
2469 | } | |||
2470 | ||||
2471 | // Handle XCore specific ABI requirements. | |||
2472 | if (getTriple().getArch() == llvm::Triple::xcore && | |||
2473 | D->getLanguageLinkage() == CLanguageLinkage && | |||
2474 | D->getType().isConstant(Context) && | |||
2475 | isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) | |||
2476 | GV->setSection(".cp.rodata"); | |||
2477 | ||||
2478 | // Check if we a have a const declaration with an initializer, we may be | |||
2479 | // able to emit it as available_externally to expose it's value to the | |||
2480 | // optimizer. | |||
2481 | if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() && | |||
2482 | D->getType().isConstQualified() && !GV->hasInitializer() && | |||
2483 | !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) { | |||
2484 | const auto *Record = | |||
2485 | Context.getBaseElementType(D->getType())->getAsCXXRecordDecl(); | |||
2486 | bool HasMutableFields = Record && Record->hasMutableFields(); | |||
2487 | if (!HasMutableFields) { | |||
2488 | const VarDecl *InitDecl; | |||
2489 | const Expr *InitExpr = D->getAnyInitializer(InitDecl); | |||
2490 | if (InitExpr) { | |||
2491 | ConstantEmitter emitter(*this); | |||
2492 | llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl); | |||
2493 | if (Init) { | |||
2494 | auto *InitType = Init->getType(); | |||
2495 | if (GV->getType()->getElementType() != InitType) { | |||
2496 | // The type of the initializer does not match the definition. | |||
2497 | // This happens when an initializer has a different type from | |||
2498 | // the type of the global (because of padding at the end of a | |||
2499 | // structure for instance). | |||
2500 | GV->setName(StringRef()); | |||
2501 | // Make a new global with the correct type, this is now guaranteed | |||
2502 | // to work. | |||
2503 | auto *NewGV = cast<llvm::GlobalVariable>( | |||
2504 | GetAddrOfGlobalVar(D, InitType, IsForDefinition)); | |||
2505 | ||||
2506 | // Erase the old global, since it is no longer used. | |||
2507 | cast<llvm::GlobalValue>(GV)->eraseFromParent(); | |||
2508 | GV = NewGV; | |||
2509 | } else { | |||
2510 | GV->setInitializer(Init); | |||
2511 | GV->setConstant(true); | |||
2512 | GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage); | |||
2513 | } | |||
2514 | emitter.finalize(GV); | |||
2515 | } | |||
2516 | } | |||
2517 | } | |||
2518 | } | |||
2519 | } | |||
2520 | ||||
2521 | LangAS ExpectedAS = | |||
2522 | D ? D->getType().getAddressSpace() | |||
2523 | : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default); | |||
2524 | assert(getContext().getTargetAddressSpace(ExpectedAS) ==(static_cast <bool> (getContext().getTargetAddressSpace (ExpectedAS) == Ty->getPointerAddressSpace()) ? void (0) : __assert_fail ("getContext().getTargetAddressSpace(ExpectedAS) == Ty->getPointerAddressSpace()" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 2525, __extension__ __PRETTY_FUNCTION__)) | |||
2525 | Ty->getPointerAddressSpace())(static_cast <bool> (getContext().getTargetAddressSpace (ExpectedAS) == Ty->getPointerAddressSpace()) ? void (0) : __assert_fail ("getContext().getTargetAddressSpace(ExpectedAS) == Ty->getPointerAddressSpace()" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 2525, __extension__ __PRETTY_FUNCTION__)); | |||
2526 | if (AddrSpace != ExpectedAS) | |||
2527 | return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace, | |||
2528 | ExpectedAS, Ty); | |||
2529 | ||||
2530 | return GV; | |||
2531 | } | |||
2532 | ||||
2533 | llvm::Constant * | |||
2534 | CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, | |||
2535 | ForDefinition_t IsForDefinition) { | |||
2536 | const Decl *D = GD.getDecl(); | |||
2537 | if (isa<CXXConstructorDecl>(D)) | |||
2538 | return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D), | |||
2539 | getFromCtorType(GD.getCtorType()), | |||
2540 | /*FnInfo=*/nullptr, /*FnType=*/nullptr, | |||
2541 | /*DontDefer=*/false, IsForDefinition); | |||
2542 | else if (isa<CXXDestructorDecl>(D)) | |||
2543 | return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D), | |||
2544 | getFromDtorType(GD.getDtorType()), | |||
2545 | /*FnInfo=*/nullptr, /*FnType=*/nullptr, | |||
2546 | /*DontDefer=*/false, IsForDefinition); | |||
2547 | else if (isa<CXXMethodDecl>(D)) { | |||
2548 | auto FInfo = &getTypes().arrangeCXXMethodDeclaration( | |||
2549 | cast<CXXMethodDecl>(D)); | |||
2550 | auto Ty = getTypes().GetFunctionType(*FInfo); | |||
2551 | return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, | |||
2552 | IsForDefinition); | |||
2553 | } else if (isa<FunctionDecl>(D)) { | |||
2554 | const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); | |||
2555 | llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); | |||
2556 | return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, | |||
2557 | IsForDefinition); | |||
2558 | } else | |||
2559 | return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, | |||
2560 | IsForDefinition); | |||
2561 | } | |||
2562 | ||||
2563 | llvm::GlobalVariable * | |||
2564 | CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name, | |||
2565 | llvm::Type *Ty, | |||
2566 | llvm::GlobalValue::LinkageTypes Linkage) { | |||
2567 | llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); | |||
2568 | llvm::GlobalVariable *OldGV = nullptr; | |||
2569 | ||||
2570 | if (GV) { | |||
2571 | // Check if the variable has the right type. | |||
2572 | if (GV->getType()->getElementType() == Ty) | |||
2573 | return GV; | |||
2574 | ||||
2575 | // Because C++ name mangling, the only way we can end up with an already | |||
2576 | // existing global with the same name is if it has been declared extern "C". | |||
2577 | assert(GV->isDeclaration() && "Declaration has wrong type!")(static_cast <bool> (GV->isDeclaration() && "Declaration has wrong type!" ) ? void (0) : __assert_fail ("GV->isDeclaration() && \"Declaration has wrong type!\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 2577, __extension__ __PRETTY_FUNCTION__)); | |||
2578 | OldGV = GV; | |||
2579 | } | |||
2580 | ||||
2581 | // Create a new variable. | |||
2582 | GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, | |||
2583 | Linkage, nullptr, Name); | |||
2584 | ||||
2585 | if (OldGV) { | |||
2586 | // Replace occurrences of the old variable if needed. | |||
2587 | GV->takeName(OldGV); | |||
2588 | ||||
2589 | if (!OldGV->use_empty()) { | |||
2590 | llvm::Constant *NewPtrForOldDecl = | |||
2591 | llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); | |||
2592 | OldGV->replaceAllUsesWith(NewPtrForOldDecl); | |||
2593 | } | |||
2594 | ||||
2595 | OldGV->eraseFromParent(); | |||
2596 | } | |||
2597 | ||||
2598 | if (supportsCOMDAT() && GV->isWeakForLinker() && | |||
2599 | !GV->hasAvailableExternallyLinkage()) | |||
2600 | GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); | |||
2601 | ||||
2602 | return GV; | |||
2603 | } | |||
2604 | ||||
2605 | /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the | |||
2606 | /// given global variable. If Ty is non-null and if the global doesn't exist, | |||
2607 | /// then it will be created with the specified type instead of whatever the | |||
2608 | /// normal requested type would be. If IsForDefinition is true, it is guranteed | |||
2609 | /// that an actual global with type Ty will be returned, not conversion of a | |||
2610 | /// variable with the same mangled name but some other type. | |||
2611 | llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, | |||
2612 | llvm::Type *Ty, | |||
2613 | ForDefinition_t IsForDefinition) { | |||
2614 | assert(D->hasGlobalStorage() && "Not a global variable")(static_cast <bool> (D->hasGlobalStorage() && "Not a global variable") ? void (0) : __assert_fail ("D->hasGlobalStorage() && \"Not a global variable\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 2614, __extension__ __PRETTY_FUNCTION__)); | |||
2615 | QualType ASTTy = D->getType(); | |||
2616 | if (!Ty) | |||
2617 | Ty = getTypes().ConvertTypeForMem(ASTTy); | |||
2618 | ||||
2619 | llvm::PointerType *PTy = | |||
2620 | llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); | |||
2621 | ||||
2622 | StringRef MangledName = getMangledName(D); | |||
2623 | return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition); | |||
2624 | } | |||
2625 | ||||
2626 | /// CreateRuntimeVariable - Create a new runtime global variable with the | |||
2627 | /// specified type and name. | |||
2628 | llvm::Constant * | |||
2629 | CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, | |||
2630 | StringRef Name) { | |||
2631 | return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr); | |||
2632 | } | |||
2633 | ||||
2634 | void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { | |||
2635 | assert(!D->getInit() && "Cannot emit definite definitions here!")(static_cast <bool> (!D->getInit() && "Cannot emit definite definitions here!" ) ? void (0) : __assert_fail ("!D->getInit() && \"Cannot emit definite definitions here!\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 2635, __extension__ __PRETTY_FUNCTION__)); | |||
2636 | ||||
2637 | StringRef MangledName = getMangledName(D); | |||
2638 | llvm::GlobalValue *GV = GetGlobalValue(MangledName); | |||
2639 | ||||
2640 | // We already have a definition, not declaration, with the same mangled name. | |||
2641 | // Emitting of declaration is not required (and actually overwrites emitted | |||
2642 | // definition). | |||
2643 | if (GV && !GV->isDeclaration()) | |||
2644 | return; | |||
2645 | ||||
2646 | // If we have not seen a reference to this variable yet, place it into the | |||
2647 | // deferred declarations table to be emitted if needed later. | |||
2648 | if (!MustBeEmitted(D) && !GV) { | |||
2649 | DeferredDecls[MangledName] = D; | |||
2650 | return; | |||
2651 | } | |||
2652 | ||||
2653 | // The tentative definition is the only definition. | |||
2654 | EmitGlobalVarDefinition(D); | |||
2655 | } | |||
2656 | ||||
2657 | CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { | |||
2658 | return Context.toCharUnitsFromBits( | |||
2659 | getDataLayout().getTypeStoreSizeInBits(Ty)); | |||
2660 | } | |||
2661 | ||||
2662 | LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) { | |||
2663 | LangAS AddrSpace = LangAS::Default; | |||
2664 | if (LangOpts.OpenCL) { | |||
2665 | AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global; | |||
2666 | assert(AddrSpace == LangAS::opencl_global ||(static_cast <bool> (AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::opencl_constant || AddrSpace == LangAS ::opencl_local || AddrSpace >= LangAS::FirstTargetAddressSpace ) ? void (0) : __assert_fail ("AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::opencl_constant || AddrSpace == LangAS::opencl_local || AddrSpace >= LangAS::FirstTargetAddressSpace" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 2669, __extension__ __PRETTY_FUNCTION__)) | |||
2667 | AddrSpace == LangAS::opencl_constant ||(static_cast <bool> (AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::opencl_constant || AddrSpace == LangAS ::opencl_local || AddrSpace >= LangAS::FirstTargetAddressSpace ) ? void (0) : __assert_fail ("AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::opencl_constant || AddrSpace == LangAS::opencl_local || AddrSpace >= LangAS::FirstTargetAddressSpace" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 2669, __extension__ __PRETTY_FUNCTION__)) | |||
2668 | AddrSpace == LangAS::opencl_local ||(static_cast <bool> (AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::opencl_constant || AddrSpace == LangAS ::opencl_local || AddrSpace >= LangAS::FirstTargetAddressSpace ) ? void (0) : __assert_fail ("AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::opencl_constant || AddrSpace == LangAS::opencl_local || AddrSpace >= LangAS::FirstTargetAddressSpace" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 2669, __extension__ __PRETTY_FUNCTION__)) | |||
2669 | AddrSpace >= LangAS::FirstTargetAddressSpace)(static_cast <bool> (AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::opencl_constant || AddrSpace == LangAS ::opencl_local || AddrSpace >= LangAS::FirstTargetAddressSpace ) ? void (0) : __assert_fail ("AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::opencl_constant || AddrSpace == LangAS::opencl_local || AddrSpace >= LangAS::FirstTargetAddressSpace" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 2669, __extension__ __PRETTY_FUNCTION__)); | |||
2670 | return AddrSpace; | |||
2671 | } | |||
2672 | ||||
2673 | if (LangOpts.CUDA && LangOpts.CUDAIsDevice) { | |||
2674 | if (D && D->hasAttr<CUDAConstantAttr>()) | |||
2675 | return LangAS::cuda_constant; | |||
2676 | else if (D && D->hasAttr<CUDASharedAttr>()) | |||
2677 | return LangAS::cuda_shared; | |||
2678 | else | |||
2679 | return LangAS::cuda_device; | |||
2680 | } | |||
2681 | ||||
2682 | return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D); | |||
2683 | } | |||
2684 | ||||
2685 | template<typename SomeDecl> | |||
2686 | void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, | |||
2687 | llvm::GlobalValue *GV) { | |||
2688 | if (!getLangOpts().CPlusPlus) | |||
2689 | return; | |||
2690 | ||||
2691 | // Must have 'used' attribute, or else inline assembly can't rely on | |||
2692 | // the name existing. | |||
2693 | if (!D->template hasAttr<UsedAttr>()) | |||
2694 | return; | |||
2695 | ||||
2696 | // Must have internal linkage and an ordinary name. | |||
2697 | if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) | |||
2698 | return; | |||
2699 | ||||
2700 | // Must be in an extern "C" context. Entities declared directly within | |||
2701 | // a record are not extern "C" even if the record is in such a context. | |||
2702 | const SomeDecl *First = D->getFirstDecl(); | |||
2703 | if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) | |||
2704 | return; | |||
2705 | ||||
2706 | // OK, this is an internal linkage entity inside an extern "C" linkage | |||
2707 | // specification. Make a note of that so we can give it the "expected" | |||
2708 | // mangled name if nothing else is using that name. | |||
2709 | std::pair<StaticExternCMap::iterator, bool> R = | |||
2710 | StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); | |||
2711 | ||||
2712 | // If we have multiple internal linkage entities with the same name | |||
2713 | // in extern "C" regions, none of them gets that name. | |||
2714 | if (!R.second) | |||
2715 | R.first->second = nullptr; | |||
2716 | } | |||
2717 | ||||
2718 | static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { | |||
2719 | if (!CGM.supportsCOMDAT()) | |||
2720 | return false; | |||
2721 | ||||
2722 | if (D.hasAttr<SelectAnyAttr>()) | |||
2723 | return true; | |||
2724 | ||||
2725 | GVALinkage Linkage; | |||
2726 | if (auto *VD = dyn_cast<VarDecl>(&D)) | |||
2727 | Linkage = CGM.getContext().GetGVALinkageForVariable(VD); | |||
2728 | else | |||
2729 | Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); | |||
2730 | ||||
2731 | switch (Linkage) { | |||
2732 | case GVA_Internal: | |||
2733 | case GVA_AvailableExternally: | |||
2734 | case GVA_StrongExternal: | |||
2735 | return false; | |||
2736 | case GVA_DiscardableODR: | |||
2737 | case GVA_StrongODR: | |||
2738 | return true; | |||
2739 | } | |||
2740 | llvm_unreachable("No such linkage")::llvm::llvm_unreachable_internal("No such linkage", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 2740); | |||
2741 | } | |||
2742 | ||||
2743 | void CodeGenModule::maybeSetTrivialComdat(const Decl &D, | |||
2744 | llvm::GlobalObject &GO) { | |||
2745 | if (!shouldBeInCOMDAT(*this, D)) | |||
2746 | return; | |||
2747 | GO.setComdat(TheModule.getOrInsertComdat(GO.getName())); | |||
2748 | } | |||
2749 | ||||
2750 | /// Pass IsTentative as true if you want to create a tentative definition. | |||
2751 | void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D, | |||
2752 | bool IsTentative) { | |||
2753 | // OpenCL global variables of sampler type are translated to function calls, | |||
2754 | // therefore no need to be translated. | |||
2755 | QualType ASTTy = D->getType(); | |||
2756 | if (getLangOpts().OpenCL && ASTTy->isSamplerT()) | |||
2757 | return; | |||
2758 | ||||
2759 | llvm::Constant *Init = nullptr; | |||
2760 | CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); | |||
2761 | bool NeedsGlobalCtor = false; | |||
2762 | bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor(); | |||
2763 | ||||
2764 | const VarDecl *InitDecl; | |||
2765 | const Expr *InitExpr = D->getAnyInitializer(InitDecl); | |||
2766 | ||||
2767 | Optional<ConstantEmitter> emitter; | |||
2768 | ||||
2769 | // CUDA E.2.4.1 "__shared__ variables cannot have an initialization | |||
2770 | // as part of their declaration." Sema has already checked for | |||
2771 | // error cases, so we just need to set Init to UndefValue. | |||
2772 | if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice && | |||
2773 | D->hasAttr<CUDASharedAttr>()) | |||
2774 | Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy)); | |||
2775 | else if (!InitExpr) { | |||
2776 | // This is a tentative definition; tentative definitions are | |||
2777 | // implicitly initialized with { 0 }. | |||
2778 | // | |||
2779 | // Note that tentative definitions are only emitted at the end of | |||
2780 | // a translation unit, so they should never have incomplete | |||
2781 | // type. In addition, EmitTentativeDefinition makes sure that we | |||
2782 | // never attempt to emit a tentative definition if a real one | |||
2783 | // exists. A use may still exists, however, so we still may need | |||
2784 | // to do a RAUW. | |||
2785 | assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type")(static_cast <bool> (!ASTTy->isIncompleteType() && "Unexpected incomplete type") ? void (0) : __assert_fail ("!ASTTy->isIncompleteType() && \"Unexpected incomplete type\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 2785, __extension__ __PRETTY_FUNCTION__)); | |||
2786 | Init = EmitNullConstant(D->getType()); | |||
2787 | } else { | |||
2788 | initializedGlobalDecl = GlobalDecl(D); | |||
2789 | emitter.emplace(*this); | |||
2790 | Init = emitter->tryEmitForInitializer(*InitDecl); | |||
2791 | ||||
2792 | if (!Init) { | |||
2793 | QualType T = InitExpr->getType(); | |||
2794 | if (D->getType()->isReferenceType()) | |||
2795 | T = D->getType(); | |||
2796 | ||||
2797 | if (getLangOpts().CPlusPlus) { | |||
2798 | Init = EmitNullConstant(T); | |||
2799 | NeedsGlobalCtor = true; | |||
2800 | } else { | |||
2801 | ErrorUnsupported(D, "static initializer"); | |||
2802 | Init = llvm::UndefValue::get(getTypes().ConvertType(T)); | |||
2803 | } | |||
2804 | } else { | |||
2805 | // We don't need an initializer, so remove the entry for the delayed | |||
2806 | // initializer position (just in case this entry was delayed) if we | |||
2807 | // also don't need to register a destructor. | |||
2808 | if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) | |||
2809 | DelayedCXXInitPosition.erase(D); | |||
2810 | } | |||
2811 | } | |||
2812 | ||||
2813 | llvm::Type* InitType = Init->getType(); | |||
2814 | llvm::Constant *Entry = | |||
2815 | GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)); | |||
2816 | ||||
2817 | // Strip off a bitcast if we got one back. | |||
2818 | if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { | |||
2819 | assert(CE->getOpcode() == llvm::Instruction::BitCast ||(static_cast <bool> (CE->getOpcode() == llvm::Instruction ::BitCast || CE->getOpcode() == llvm::Instruction::AddrSpaceCast || CE->getOpcode() == llvm::Instruction::GetElementPtr) ? void (0) : __assert_fail ("CE->getOpcode() == llvm::Instruction::BitCast || CE->getOpcode() == llvm::Instruction::AddrSpaceCast || CE->getOpcode() == llvm::Instruction::GetElementPtr" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 2822, __extension__ __PRETTY_FUNCTION__)) | |||
2820 | CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||(static_cast <bool> (CE->getOpcode() == llvm::Instruction ::BitCast || CE->getOpcode() == llvm::Instruction::AddrSpaceCast || CE->getOpcode() == llvm::Instruction::GetElementPtr) ? void (0) : __assert_fail ("CE->getOpcode() == llvm::Instruction::BitCast || CE->getOpcode() == llvm::Instruction::AddrSpaceCast || CE->getOpcode() == llvm::Instruction::GetElementPtr" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 2822, __extension__ __PRETTY_FUNCTION__)) | |||
2821 | // All zero index gep.(static_cast <bool> (CE->getOpcode() == llvm::Instruction ::BitCast || CE->getOpcode() == llvm::Instruction::AddrSpaceCast || CE->getOpcode() == llvm::Instruction::GetElementPtr) ? void (0) : __assert_fail ("CE->getOpcode() == llvm::Instruction::BitCast || CE->getOpcode() == llvm::Instruction::AddrSpaceCast || CE->getOpcode() == llvm::Instruction::GetElementPtr" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 2822, __extension__ __PRETTY_FUNCTION__)) | |||
2822 | CE->getOpcode() == llvm::Instruction::GetElementPtr)(static_cast <bool> (CE->getOpcode() == llvm::Instruction ::BitCast || CE->getOpcode() == llvm::Instruction::AddrSpaceCast || CE->getOpcode() == llvm::Instruction::GetElementPtr) ? void (0) : __assert_fail ("CE->getOpcode() == llvm::Instruction::BitCast || CE->getOpcode() == llvm::Instruction::AddrSpaceCast || CE->getOpcode() == llvm::Instruction::GetElementPtr" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 2822, __extension__ __PRETTY_FUNCTION__)); | |||
2823 | Entry = CE->getOperand(0); | |||
2824 | } | |||
2825 | ||||
2826 | // Entry is now either a Function or GlobalVariable. | |||
2827 | auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); | |||
2828 | ||||
2829 | // We have a definition after a declaration with the wrong type. | |||
2830 | // We must make a new GlobalVariable* and update everything that used OldGV | |||
2831 | // (a declaration or tentative definition) with the new GlobalVariable* | |||
2832 | // (which will be a definition). | |||
2833 | // | |||
2834 | // This happens if there is a prototype for a global (e.g. | |||
2835 | // "extern int x[];") and then a definition of a different type (e.g. | |||
2836 | // "int x[10];"). This also happens when an initializer has a different type | |||
2837 | // from the type of the global (this happens with unions). | |||
2838 | if (!GV || GV->getType()->getElementType() != InitType || | |||
2839 | GV->getType()->getAddressSpace() != | |||
2840 | getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) { | |||
2841 | ||||
2842 | // Move the old entry aside so that we'll create a new one. | |||
2843 | Entry->setName(StringRef()); | |||
2844 | ||||
2845 | // Make a new global with the correct type, this is now guaranteed to work. | |||
2846 | GV = cast<llvm::GlobalVariable>( | |||
2847 | GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))); | |||
2848 | ||||
2849 | // Replace all uses of the old global with the new global | |||
2850 | llvm::Constant *NewPtrForOldDecl = | |||
2851 | llvm::ConstantExpr::getBitCast(GV, Entry->getType()); | |||
2852 | Entry->replaceAllUsesWith(NewPtrForOldDecl); | |||
2853 | ||||
2854 | // Erase the old global, since it is no longer used. | |||
2855 | cast<llvm::GlobalValue>(Entry)->eraseFromParent(); | |||
2856 | } | |||
2857 | ||||
2858 | MaybeHandleStaticInExternC(D, GV); | |||
2859 | ||||
2860 | if (D->hasAttr<AnnotateAttr>()) | |||
2861 | AddGlobalAnnotations(D, GV); | |||
2862 | ||||
2863 | // Set the llvm linkage type as appropriate. | |||
2864 | llvm::GlobalValue::LinkageTypes Linkage = | |||
2865 | getLLVMLinkageVarDefinition(D, GV->isConstant()); | |||
2866 | ||||
2867 | // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on | |||
2868 | // the device. [...]" | |||
2869 | // CUDA B.2.2 "The __constant__ qualifier, optionally used together with | |||
2870 | // __device__, declares a variable that: [...] | |||
2871 | // Is accessible from all the threads within the grid and from the host | |||
2872 | // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() | |||
2873 | // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." | |||
2874 | if (GV && LangOpts.CUDA) { | |||
2875 | if (LangOpts.CUDAIsDevice) { | |||
2876 | if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) | |||
2877 | GV->setExternallyInitialized(true); | |||
2878 | } else { | |||
2879 | // Host-side shadows of external declarations of device-side | |||
2880 | // global variables become internal definitions. These have to | |||
2881 | // be internal in order to prevent name conflicts with global | |||
2882 | // host variables with the same name in a different TUs. | |||
2883 | if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) { | |||
2884 | Linkage = llvm::GlobalValue::InternalLinkage; | |||
2885 | ||||
2886 | // Shadow variables and their properties must be registered | |||
2887 | // with CUDA runtime. | |||
2888 | unsigned Flags = 0; | |||
2889 | if (!D->hasDefinition()) | |||
2890 | Flags |= CGCUDARuntime::ExternDeviceVar; | |||
2891 | if (D->hasAttr<CUDAConstantAttr>()) | |||
2892 | Flags |= CGCUDARuntime::ConstantDeviceVar; | |||
2893 | getCUDARuntime().registerDeviceVar(*GV, Flags); | |||
2894 | } else if (D->hasAttr<CUDASharedAttr>()) | |||
2895 | // __shared__ variables are odd. Shadows do get created, but | |||
2896 | // they are not registered with the CUDA runtime, so they | |||
2897 | // can't really be used to access their device-side | |||
2898 | // counterparts. It's not clear yet whether it's nvcc's bug or | |||
2899 | // a feature, but we've got to do the same for compatibility. | |||
2900 | Linkage = llvm::GlobalValue::InternalLinkage; | |||
2901 | } | |||
2902 | } | |||
2903 | ||||
2904 | GV->setInitializer(Init); | |||
2905 | if (emitter) emitter->finalize(GV); | |||
2906 | ||||
2907 | // If it is safe to mark the global 'constant', do so now. | |||
2908 | GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && | |||
2909 | isTypeConstant(D->getType(), true)); | |||
2910 | ||||
2911 | // If it is in a read-only section, mark it 'constant'. | |||
2912 | if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { | |||
2913 | const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; | |||
2914 | if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) | |||
2915 | GV->setConstant(true); | |||
2916 | } | |||
2917 | ||||
2918 | GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); | |||
2919 | ||||
2920 | ||||
2921 | // On Darwin, if the normal linkage of a C++ thread_local variable is | |||
2922 | // LinkOnce or Weak, we keep the normal linkage to prevent multiple | |||
2923 | // copies within a linkage unit; otherwise, the backing variable has | |||
2924 | // internal linkage and all accesses should just be calls to the | |||
2925 | // Itanium-specified entry point, which has the normal linkage of the | |||
2926 | // variable. This is to preserve the ability to change the implementation | |||
2927 | // behind the scenes. | |||
2928 | if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic && | |||
2929 | Context.getTargetInfo().getTriple().isOSDarwin() && | |||
2930 | !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) && | |||
2931 | !llvm::GlobalVariable::isWeakLinkage(Linkage)) | |||
2932 | Linkage = llvm::GlobalValue::InternalLinkage; | |||
2933 | ||||
2934 | GV->setLinkage(Linkage); | |||
2935 | if (D->hasAttr<DLLImportAttr>()) | |||
2936 | GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); | |||
2937 | else if (D->hasAttr<DLLExportAttr>()) | |||
2938 | GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); | |||
2939 | else | |||
2940 | GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); | |||
2941 | ||||
2942 | if (Linkage == llvm::GlobalVariable::CommonLinkage) { | |||
2943 | // common vars aren't constant even if declared const. | |||
2944 | GV->setConstant(false); | |||
2945 | // Tentative definition of global variables may be initialized with | |||
2946 | // non-zero null pointers. In this case they should have weak linkage | |||
2947 | // since common linkage must have zero initializer and must not have | |||
2948 | // explicit section therefore cannot have non-zero initial value. | |||
2949 | if (!GV->getInitializer()->isNullValue()) | |||
2950 | GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); | |||
2951 | } | |||
2952 | ||||
2953 | setNonAliasAttributes(D, GV); | |||
2954 | ||||
2955 | if (D->getTLSKind() && !GV->isThreadLocal()) { | |||
2956 | if (D->getTLSKind() == VarDecl::TLS_Dynamic) | |||
2957 | CXXThreadLocals.push_back(D); | |||
2958 | setTLSMode(GV, *D); | |||
2959 | } | |||
2960 | ||||
2961 | maybeSetTrivialComdat(*D, *GV); | |||
2962 | ||||
2963 | // Emit the initializer function if necessary. | |||
2964 | if (NeedsGlobalCtor || NeedsGlobalDtor) | |||
2965 | EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); | |||
2966 | ||||
2967 | SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor); | |||
2968 | ||||
2969 | // Emit global variable debug information. | |||
2970 | if (CGDebugInfo *DI = getModuleDebugInfo()) | |||
2971 | if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) | |||
2972 | DI->EmitGlobalVariable(GV, D); | |||
2973 | } | |||
2974 | ||||
2975 | static bool isVarDeclStrongDefinition(const ASTContext &Context, | |||
2976 | CodeGenModule &CGM, const VarDecl *D, | |||
2977 | bool NoCommon) { | |||
2978 | // Don't give variables common linkage if -fno-common was specified unless it | |||
2979 | // was overridden by a NoCommon attribute. | |||
2980 | if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) | |||
2981 | return true; | |||
2982 | ||||
2983 | // C11 6.9.2/2: | |||
2984 | // A declaration of an identifier for an object that has file scope without | |||
2985 | // an initializer, and without a storage-class specifier or with the | |||
2986 | // storage-class specifier static, constitutes a tentative definition. | |||
2987 | if (D->getInit() || D->hasExternalStorage()) | |||
2988 | return true; | |||
2989 | ||||
2990 | // A variable cannot be both common and exist in a section. | |||
2991 | if (D->hasAttr<SectionAttr>()) | |||
2992 | return true; | |||
2993 | ||||
2994 | // A variable cannot be both common and exist in a section. | |||
2995 | // We dont try to determine which is the right section in the front-end. | |||
2996 | // If no specialized section name is applicable, it will resort to default. | |||
2997 | if (D->hasAttr<PragmaClangBSSSectionAttr>() || | |||
2998 | D->hasAttr<PragmaClangDataSectionAttr>() || | |||
2999 | D->hasAttr<PragmaClangRodataSectionAttr>()) | |||
3000 | return true; | |||
3001 | ||||
3002 | // Thread local vars aren't considered common linkage. | |||
3003 | if (D->getTLSKind()) | |||
3004 | return true; | |||
3005 | ||||
3006 | // Tentative definitions marked with WeakImportAttr are true definitions. | |||
3007 | if (D->hasAttr<WeakImportAttr>()) | |||
3008 | return true; | |||
3009 | ||||
3010 | // A variable cannot be both common and exist in a comdat. | |||
3011 | if (shouldBeInCOMDAT(CGM, *D)) | |||
3012 | return true; | |||
3013 | ||||
3014 | // Declarations with a required alignment do not have common linkage in MSVC | |||
3015 | // mode. | |||
3016 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { | |||
3017 | if (D->hasAttr<AlignedAttr>()) | |||
3018 | return true; | |||
3019 | QualType VarType = D->getType(); | |||
3020 | if (Context.isAlignmentRequired(VarType)) | |||
3021 | return true; | |||
3022 | ||||
3023 | if (const auto *RT = VarType->getAs<RecordType>()) { | |||
3024 | const RecordDecl *RD = RT->getDecl(); | |||
3025 | for (const FieldDecl *FD : RD->fields()) { | |||
3026 | if (FD->isBitField()) | |||
3027 | continue; | |||
3028 | if (FD->hasAttr<AlignedAttr>()) | |||
3029 | return true; | |||
3030 | if (Context.isAlignmentRequired(FD->getType())) | |||
3031 | return true; | |||
3032 | } | |||
3033 | } | |||
3034 | } | |||
3035 | ||||
3036 | return false; | |||
3037 | } | |||
3038 | ||||
3039 | llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator( | |||
3040 | const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) { | |||
3041 | if (Linkage == GVA_Internal) | |||
3042 | return llvm::Function::InternalLinkage; | |||
3043 | ||||
3044 | if (D->hasAttr<WeakAttr>()) { | |||
3045 | if (IsConstantVariable) | |||
3046 | return llvm::GlobalVariable::WeakODRLinkage; | |||
3047 | else | |||
3048 | return llvm::GlobalVariable::WeakAnyLinkage; | |||
3049 | } | |||
3050 | ||||
3051 | // We are guaranteed to have a strong definition somewhere else, | |||
3052 | // so we can use available_externally linkage. | |||
3053 | if (Linkage == GVA_AvailableExternally) | |||
3054 | return llvm::GlobalValue::AvailableExternallyLinkage; | |||
3055 | ||||
3056 | // Note that Apple's kernel linker doesn't support symbol | |||
3057 | // coalescing, so we need to avoid linkonce and weak linkages there. | |||
3058 | // Normally, this means we just map to internal, but for explicit | |||
3059 | // instantiations we'll map to external. | |||
3060 | ||||
3061 | // In C++, the compiler has to emit a definition in every translation unit | |||
3062 | // that references the function. We should use linkonce_odr because | |||
3063 | // a) if all references in this translation unit are optimized away, we | |||
3064 | // don't need to codegen it. b) if the function persists, it needs to be | |||
3065 | // merged with other definitions. c) C++ has the ODR, so we know the | |||
3066 | // definition is dependable. | |||
3067 | if (Linkage == GVA_DiscardableODR) | |||
3068 | return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage | |||
3069 | : llvm::Function::InternalLinkage; | |||
3070 | ||||
3071 | // An explicit instantiation of a template has weak linkage, since | |||
3072 | // explicit instantiations can occur in multiple translation units | |||
3073 | // and must all be equivalent. However, we are not allowed to | |||
3074 | // throw away these explicit instantiations. | |||
3075 | // | |||
3076 | // We don't currently support CUDA device code spread out across multiple TUs, | |||
3077 | // so say that CUDA templates are either external (for kernels) or internal. | |||
3078 | // This lets llvm perform aggressive inter-procedural optimizations. | |||
3079 | if (Linkage == GVA_StrongODR) { | |||
3080 | if (Context.getLangOpts().AppleKext) | |||
3081 | return llvm::Function::ExternalLinkage; | |||
3082 | if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) | |||
3083 | return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage | |||
3084 | : llvm::Function::InternalLinkage; | |||
3085 | return llvm::Function::WeakODRLinkage; | |||
3086 | } | |||
3087 | ||||
3088 | // C++ doesn't have tentative definitions and thus cannot have common | |||
3089 | // linkage. | |||
3090 | if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && | |||
3091 | !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D), | |||
3092 | CodeGenOpts.NoCommon)) | |||
3093 | return llvm::GlobalVariable::CommonLinkage; | |||
3094 | ||||
3095 | // selectany symbols are externally visible, so use weak instead of | |||
3096 | // linkonce. MSVC optimizes away references to const selectany globals, so | |||
3097 | // all definitions should be the same and ODR linkage should be used. | |||
3098 | // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx | |||
3099 | if (D->hasAttr<SelectAnyAttr>()) | |||
3100 | return llvm::GlobalVariable::WeakODRLinkage; | |||
3101 | ||||
3102 | // Otherwise, we have strong external linkage. | |||
3103 | assert(Linkage == GVA_StrongExternal)(static_cast <bool> (Linkage == GVA_StrongExternal) ? void (0) : __assert_fail ("Linkage == GVA_StrongExternal", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 3103, __extension__ __PRETTY_FUNCTION__)); | |||
3104 | return llvm::GlobalVariable::ExternalLinkage; | |||
3105 | } | |||
3106 | ||||
3107 | llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition( | |||
3108 | const VarDecl *VD, bool IsConstant) { | |||
3109 | GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); | |||
3110 | return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant); | |||
3111 | } | |||
3112 | ||||
3113 | /// Replace the uses of a function that was declared with a non-proto type. | |||
3114 | /// We want to silently drop extra arguments from call sites | |||
3115 | static void replaceUsesOfNonProtoConstant(llvm::Constant *old, | |||
3116 | llvm::Function *newFn) { | |||
3117 | // Fast path. | |||
3118 | if (old->use_empty()) return; | |||
3119 | ||||
3120 | llvm::Type *newRetTy = newFn->getReturnType(); | |||
3121 | SmallVector<llvm::Value*, 4> newArgs; | |||
3122 | SmallVector<llvm::OperandBundleDef, 1> newBundles; | |||
3123 | ||||
3124 | for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); | |||
3125 | ui != ue; ) { | |||
3126 | llvm::Value::use_iterator use = ui++; // Increment before the use is erased. | |||
3127 | llvm::User *user = use->getUser(); | |||
3128 | ||||
3129 | // Recognize and replace uses of bitcasts. Most calls to | |||
3130 | // unprototyped functions will use bitcasts. | |||
3131 | if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { | |||
3132 | if (bitcast->getOpcode() == llvm::Instruction::BitCast) | |||
3133 | replaceUsesOfNonProtoConstant(bitcast, newFn); | |||
3134 | continue; | |||
3135 | } | |||
3136 | ||||
3137 | // Recognize calls to the function. | |||
3138 | llvm::CallSite callSite(user); | |||
3139 | if (!callSite) continue; | |||
3140 | if (!callSite.isCallee(&*use)) continue; | |||
3141 | ||||
3142 | // If the return types don't match exactly, then we can't | |||
3143 | // transform this call unless it's dead. | |||
3144 | if (callSite->getType() != newRetTy && !callSite->use_empty()) | |||
3145 | continue; | |||
3146 | ||||
3147 | // Get the call site's attribute list. | |||
3148 | SmallVector<llvm::AttributeSet, 8> newArgAttrs; | |||
3149 | llvm::AttributeList oldAttrs = callSite.getAttributes(); | |||
3150 | ||||
3151 | // If the function was passed too few arguments, don't transform. | |||
3152 | unsigned newNumArgs = newFn->arg_size(); | |||
3153 | if (callSite.arg_size() < newNumArgs) continue; | |||
3154 | ||||
3155 | // If extra arguments were passed, we silently drop them. | |||
3156 | // If any of the types mismatch, we don't transform. | |||
3157 | unsigned argNo = 0; | |||
3158 | bool dontTransform = false; | |||
3159 | for (llvm::Argument &A : newFn->args()) { | |||
3160 | if (callSite.getArgument(argNo)->getType() != A.getType()) { | |||
3161 | dontTransform = true; | |||
3162 | break; | |||
3163 | } | |||
3164 | ||||
3165 | // Add any parameter attributes. | |||
3166 | newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo)); | |||
3167 | argNo++; | |||
3168 | } | |||
3169 | if (dontTransform) | |||
3170 | continue; | |||
3171 | ||||
3172 | // Okay, we can transform this. Create the new call instruction and copy | |||
3173 | // over the required information. | |||
3174 | newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo); | |||
3175 | ||||
3176 | // Copy over any operand bundles. | |||
3177 | callSite.getOperandBundlesAsDefs(newBundles); | |||
3178 | ||||
3179 | llvm::CallSite newCall; | |||
3180 | if (callSite.isCall()) { | |||
3181 | newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "", | |||
3182 | callSite.getInstruction()); | |||
3183 | } else { | |||
3184 | auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction()); | |||
3185 | newCall = llvm::InvokeInst::Create(newFn, | |||
3186 | oldInvoke->getNormalDest(), | |||
3187 | oldInvoke->getUnwindDest(), | |||
3188 | newArgs, newBundles, "", | |||
3189 | callSite.getInstruction()); | |||
3190 | } | |||
3191 | newArgs.clear(); // for the next iteration | |||
3192 | ||||
3193 | if (!newCall->getType()->isVoidTy()) | |||
3194 | newCall->takeName(callSite.getInstruction()); | |||
3195 | newCall.setAttributes(llvm::AttributeList::get( | |||
3196 | newFn->getContext(), oldAttrs.getFnAttributes(), | |||
3197 | oldAttrs.getRetAttributes(), newArgAttrs)); | |||
3198 | newCall.setCallingConv(callSite.getCallingConv()); | |||
3199 | ||||
3200 | // Finally, remove the old call, replacing any uses with the new one. | |||
3201 | if (!callSite->use_empty()) | |||
3202 | callSite->replaceAllUsesWith(newCall.getInstruction()); | |||
3203 | ||||
3204 | // Copy debug location attached to CI. | |||
3205 | if (callSite->getDebugLoc()) | |||
3206 | newCall->setDebugLoc(callSite->getDebugLoc()); | |||
3207 | ||||
3208 | callSite->eraseFromParent(); | |||
3209 | } | |||
3210 | } | |||
3211 | ||||
3212 | /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we | |||
3213 | /// implement a function with no prototype, e.g. "int foo() {}". If there are | |||
3214 | /// existing call uses of the old function in the module, this adjusts them to | |||
3215 | /// call the new function directly. | |||
3216 | /// | |||
3217 | /// This is not just a cleanup: the always_inline pass requires direct calls to | |||
3218 | /// functions to be able to inline them. If there is a bitcast in the way, it | |||
3219 | /// won't inline them. Instcombine normally deletes these calls, but it isn't | |||
3220 | /// run at -O0. | |||
3221 | static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, | |||
3222 | llvm::Function *NewFn) { | |||
3223 | // If we're redefining a global as a function, don't transform it. | |||
3224 | if (!isa<llvm::Function>(Old)) return; | |||
3225 | ||||
3226 | replaceUsesOfNonProtoConstant(Old, NewFn); | |||
3227 | } | |||
3228 | ||||
3229 | void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { | |||
3230 | auto DK = VD->isThisDeclarationADefinition(); | |||
3231 | if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>()) | |||
3232 | return; | |||
3233 | ||||
3234 | TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); | |||
3235 | // If we have a definition, this might be a deferred decl. If the | |||
3236 | // instantiation is explicit, make sure we emit it at the end. | |||
3237 | if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) | |||
3238 | GetAddrOfGlobalVar(VD); | |||
3239 | ||||
3240 | EmitTopLevelDecl(VD); | |||
3241 | } | |||
3242 | ||||
3243 | void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, | |||
3244 | llvm::GlobalValue *GV) { | |||
3245 | const auto *D = cast<FunctionDecl>(GD.getDecl()); | |||
3246 | ||||
3247 | // Compute the function info and LLVM type. | |||
3248 | const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); | |||
3249 | llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); | |||
3250 | ||||
3251 | // Get or create the prototype for the function. | |||
3252 | if (!GV || (GV->getType()->getElementType() != Ty)) | |||
3253 | GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, | |||
3254 | /*DontDefer=*/true, | |||
3255 | ForDefinition)); | |||
3256 | ||||
3257 | // Already emitted. | |||
3258 | if (!GV->isDeclaration()) | |||
3259 | return; | |||
3260 | ||||
3261 | // We need to set linkage and visibility on the function before | |||
3262 | // generating code for it because various parts of IR generation | |||
3263 | // want to propagate this information down (e.g. to local static | |||
3264 | // declarations). | |||
3265 | auto *Fn = cast<llvm::Function>(GV); | |||
3266 | setFunctionLinkage(GD, Fn); | |||
3267 | setFunctionDLLStorageClass(GD, Fn); | |||
3268 | ||||
3269 | // FIXME: this is redundant with part of setFunctionDefinitionAttributes | |||
3270 | setGlobalVisibility(Fn, D, ForDefinition); | |||
3271 | ||||
3272 | MaybeHandleStaticInExternC(D, Fn); | |||
3273 | ||||
3274 | maybeSetTrivialComdat(*D, *Fn); | |||
3275 | ||||
3276 | CodeGenFunction(*this).GenerateCode(D, Fn, FI); | |||
3277 | ||||
3278 | setFunctionDefinitionAttributes(D, Fn); | |||
3279 | SetLLVMFunctionAttributesForDefinition(D, Fn); | |||
3280 | ||||
3281 | if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) | |||
3282 | AddGlobalCtor(Fn, CA->getPriority()); | |||
3283 | if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) | |||
3284 | AddGlobalDtor(Fn, DA->getPriority()); | |||
3285 | if (D->hasAttr<AnnotateAttr>()) | |||
3286 | AddGlobalAnnotations(D, Fn); | |||
3287 | } | |||
3288 | ||||
3289 | void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { | |||
3290 | const auto *D = cast<ValueDecl>(GD.getDecl()); | |||
3291 | const AliasAttr *AA = D->getAttr<AliasAttr>(); | |||
3292 | assert(AA && "Not an alias?")(static_cast <bool> (AA && "Not an alias?") ? void (0) : __assert_fail ("AA && \"Not an alias?\"", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 3292, __extension__ __PRETTY_FUNCTION__)); | |||
3293 | ||||
3294 | StringRef MangledName = getMangledName(GD); | |||
3295 | ||||
3296 | if (AA->getAliasee() == MangledName) { | |||
3297 | Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; | |||
3298 | return; | |||
3299 | } | |||
3300 | ||||
3301 | // If there is a definition in the module, then it wins over the alias. | |||
3302 | // This is dubious, but allow it to be safe. Just ignore the alias. | |||
3303 | llvm::GlobalValue *Entry = GetGlobalValue(MangledName); | |||
3304 | if (Entry && !Entry->isDeclaration()) | |||
3305 | return; | |||
3306 | ||||
3307 | Aliases.push_back(GD); | |||
3308 | ||||
3309 | llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); | |||
3310 | ||||
3311 | // Create a reference to the named value. This ensures that it is emitted | |||
3312 | // if a deferred decl. | |||
3313 | llvm::Constant *Aliasee; | |||
3314 | if (isa<llvm::FunctionType>(DeclTy)) | |||
3315 | Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, | |||
3316 | /*ForVTable=*/false); | |||
3317 | else | |||
3318 | Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), | |||
3319 | llvm::PointerType::getUnqual(DeclTy), | |||
3320 | /*D=*/nullptr); | |||
3321 | ||||
3322 | // Create the new alias itself, but don't set a name yet. | |||
3323 | auto *GA = llvm::GlobalAlias::create( | |||
3324 | DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule()); | |||
3325 | ||||
3326 | if (Entry) { | |||
3327 | if (GA->getAliasee() == Entry) { | |||
3328 | Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; | |||
3329 | return; | |||
3330 | } | |||
3331 | ||||
3332 | assert(Entry->isDeclaration())(static_cast <bool> (Entry->isDeclaration()) ? void ( 0) : __assert_fail ("Entry->isDeclaration()", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 3332, __extension__ __PRETTY_FUNCTION__)); | |||
3333 | ||||
3334 | // If there is a declaration in the module, then we had an extern followed | |||
3335 | // by the alias, as in: | |||
3336 | // extern int test6(); | |||
3337 | // ... | |||
3338 | // int test6() __attribute__((alias("test7"))); | |||
3339 | // | |||
3340 | // Remove it and replace uses of it with the alias. | |||
3341 | GA->takeName(Entry); | |||
3342 | ||||
3343 | Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, | |||
3344 | Entry->getType())); | |||
3345 | Entry->eraseFromParent(); | |||
3346 | } else { | |||
3347 | GA->setName(MangledName); | |||
3348 | } | |||
3349 | ||||
3350 | // Set attributes which are particular to an alias; this is a | |||
3351 | // specialization of the attributes which may be set on a global | |||
3352 | // variable/function. | |||
3353 | if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || | |||
3354 | D->isWeakImported()) { | |||
3355 | GA->setLinkage(llvm::Function::WeakAnyLinkage); | |||
3356 | } | |||
3357 | ||||
3358 | if (const auto *VD = dyn_cast<VarDecl>(D)) | |||
3359 | if (VD->getTLSKind()) | |||
3360 | setTLSMode(GA, *VD); | |||
3361 | ||||
3362 | setAliasAttributes(D, GA); | |||
3363 | } | |||
3364 | ||||
3365 | void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) { | |||
3366 | const auto *D = cast<ValueDecl>(GD.getDecl()); | |||
3367 | const IFuncAttr *IFA = D->getAttr<IFuncAttr>(); | |||
3368 | assert(IFA && "Not an ifunc?")(static_cast <bool> (IFA && "Not an ifunc?") ? void (0) : __assert_fail ("IFA && \"Not an ifunc?\"", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 3368, __extension__ __PRETTY_FUNCTION__)); | |||
3369 | ||||
3370 | StringRef MangledName = getMangledName(GD); | |||
3371 | ||||
3372 | if (IFA->getResolver() == MangledName) { | |||
3373 | Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; | |||
3374 | return; | |||
3375 | } | |||
3376 | ||||
3377 | // Report an error if some definition overrides ifunc. | |||
3378 | llvm::GlobalValue *Entry = GetGlobalValue(MangledName); | |||
3379 | if (Entry && !Entry->isDeclaration()) { | |||
3380 | GlobalDecl OtherGD; | |||
3381 | if (lookupRepresentativeDecl(MangledName, OtherGD) && | |||
3382 | DiagnosedConflictingDefinitions.insert(GD).second) { | |||
3383 | Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name); | |||
3384 | Diags.Report(OtherGD.getDecl()->getLocation(), | |||
3385 | diag::note_previous_definition); | |||
3386 | } | |||
3387 | return; | |||
3388 | } | |||
3389 | ||||
3390 | Aliases.push_back(GD); | |||
3391 | ||||
3392 | llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); | |||
3393 | llvm::Constant *Resolver = | |||
3394 | GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD, | |||
3395 | /*ForVTable=*/false); | |||
3396 | llvm::GlobalIFunc *GIF = | |||
3397 | llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage, | |||
3398 | "", Resolver, &getModule()); | |||
3399 | if (Entry) { | |||
3400 | if (GIF->getResolver() == Entry) { | |||
3401 | Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; | |||
3402 | return; | |||
3403 | } | |||
3404 | assert(Entry->isDeclaration())(static_cast <bool> (Entry->isDeclaration()) ? void ( 0) : __assert_fail ("Entry->isDeclaration()", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 3404, __extension__ __PRETTY_FUNCTION__)); | |||
3405 | ||||
3406 | // If there is a declaration in the module, then we had an extern followed | |||
3407 | // by the ifunc, as in: | |||
3408 | // extern int test(); | |||
3409 | // ... | |||
3410 | // int test() __attribute__((ifunc("resolver"))); | |||
3411 | // | |||
3412 | // Remove it and replace uses of it with the ifunc. | |||
3413 | GIF->takeName(Entry); | |||
3414 | ||||
3415 | Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF, | |||
3416 | Entry->getType())); | |||
3417 | Entry->eraseFromParent(); | |||
3418 | } else | |||
3419 | GIF->setName(MangledName); | |||
3420 | ||||
3421 | SetCommonAttributes(D, GIF); | |||
3422 | } | |||
3423 | ||||
3424 | llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, | |||
3425 | ArrayRef<llvm::Type*> Tys) { | |||
3426 | return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, | |||
3427 | Tys); | |||
3428 | } | |||
3429 | ||||
3430 | static llvm::StringMapEntry<llvm::GlobalVariable *> & | |||
3431 | GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, | |||
3432 | const StringLiteral *Literal, bool TargetIsLSB, | |||
3433 | bool &IsUTF16, unsigned &StringLength) { | |||
3434 | StringRef String = Literal->getString(); | |||
3435 | unsigned NumBytes = String.size(); | |||
3436 | ||||
3437 | // Check for simple case. | |||
3438 | if (!Literal->containsNonAsciiOrNull()) { | |||
3439 | StringLength = NumBytes; | |||
3440 | return *Map.insert(std::make_pair(String, nullptr)).first; | |||
3441 | } | |||
3442 | ||||
3443 | // Otherwise, convert the UTF8 literals into a string of shorts. | |||
3444 | IsUTF16 = true; | |||
3445 | ||||
3446 | SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. | |||
3447 | const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); | |||
3448 | llvm::UTF16 *ToPtr = &ToBuf[0]; | |||
3449 | ||||
3450 | (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, | |||
3451 | ToPtr + NumBytes, llvm::strictConversion); | |||
3452 | ||||
3453 | // ConvertUTF8toUTF16 returns the length in ToPtr. | |||
3454 | StringLength = ToPtr - &ToBuf[0]; | |||
3455 | ||||
3456 | // Add an explicit null. | |||
3457 | *ToPtr = 0; | |||
3458 | return *Map.insert(std::make_pair( | |||
3459 | StringRef(reinterpret_cast<const char *>(ToBuf.data()), | |||
3460 | (StringLength + 1) * 2), | |||
3461 | nullptr)).first; | |||
3462 | } | |||
3463 | ||||
3464 | ConstantAddress | |||
3465 | CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { | |||
3466 | unsigned StringLength = 0; | |||
3467 | bool isUTF16 = false; | |||
3468 | llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = | |||
3469 | GetConstantCFStringEntry(CFConstantStringMap, Literal, | |||
3470 | getDataLayout().isLittleEndian(), isUTF16, | |||
3471 | StringLength); | |||
3472 | ||||
3473 | if (auto *C = Entry.second) | |||
3474 | return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment())); | |||
3475 | ||||
3476 | llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); | |||
3477 | llvm::Constant *Zeros[] = { Zero, Zero }; | |||
3478 | ||||
3479 | // If we don't already have it, get __CFConstantStringClassReference. | |||
3480 | if (!CFConstantStringClassRef) { | |||
3481 | llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); | |||
3482 | Ty = llvm::ArrayType::get(Ty, 0); | |||
3483 | llvm::Constant *GV = | |||
3484 | CreateRuntimeVariable(Ty, "__CFConstantStringClassReference"); | |||
3485 | ||||
3486 | if (getTriple().isOSBinFormatCOFF()) { | |||
3487 | IdentifierInfo &II = getContext().Idents.get(GV->getName()); | |||
3488 | TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl(); | |||
3489 | DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); | |||
3490 | llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV); | |||
3491 | ||||
3492 | const VarDecl *VD = nullptr; | |||
3493 | for (const auto &Result : DC->lookup(&II)) | |||
3494 | if ((VD = dyn_cast<VarDecl>(Result))) | |||
3495 | break; | |||
3496 | ||||
3497 | if (!VD || !VD->hasAttr<DLLExportAttr>()) { | |||
3498 | CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); | |||
3499 | CGV->setLinkage(llvm::GlobalValue::ExternalLinkage); | |||
3500 | } else { | |||
3501 | CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); | |||
3502 | CGV->setLinkage(llvm::GlobalValue::ExternalLinkage); | |||
3503 | } | |||
3504 | } | |||
3505 | ||||
3506 | // Decay array -> ptr | |||
3507 | CFConstantStringClassRef = | |||
3508 | llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros); | |||
3509 | } | |||
3510 | ||||
3511 | QualType CFTy = getContext().getCFConstantStringType(); | |||
3512 | ||||
3513 | auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); | |||
3514 | ||||
3515 | ConstantInitBuilder Builder(*this); | |||
3516 | auto Fields = Builder.beginStruct(STy); | |||
3517 | ||||
3518 | // Class pointer. | |||
3519 | Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef)); | |||
3520 | ||||
3521 | // Flags. | |||
3522 | Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8); | |||
3523 | ||||
3524 | // String pointer. | |||
3525 | llvm::Constant *C = nullptr; | |||
3526 | if (isUTF16) { | |||
3527 | auto Arr = llvm::makeArrayRef( | |||
3528 | reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), | |||
3529 | Entry.first().size() / 2); | |||
3530 | C = llvm::ConstantDataArray::get(VMContext, Arr); | |||
3531 | } else { | |||
3532 | C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); | |||
3533 | } | |||
3534 | ||||
3535 | // Note: -fwritable-strings doesn't make the backing store strings of | |||
3536 | // CFStrings writable. (See <rdar://problem/10657500>) | |||
3537 | auto *GV = | |||
3538 | new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, | |||
3539 | llvm::GlobalValue::PrivateLinkage, C, ".str"); | |||
3540 | GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); | |||
3541 | // Don't enforce the target's minimum global alignment, since the only use | |||
3542 | // of the string is via this class initializer. | |||
3543 | CharUnits Align = isUTF16 | |||
3544 | ? getContext().getTypeAlignInChars(getContext().ShortTy) | |||
3545 | : getContext().getTypeAlignInChars(getContext().CharTy); | |||
3546 | GV->setAlignment(Align.getQuantity()); | |||
3547 | ||||
3548 | // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. | |||
3549 | // Without it LLVM can merge the string with a non unnamed_addr one during | |||
3550 | // LTO. Doing that changes the section it ends in, which surprises ld64. | |||
3551 | if (getTriple().isOSBinFormatMachO()) | |||
3552 | GV->setSection(isUTF16 ? "__TEXT,__ustring" | |||
3553 | : "__TEXT,__cstring,cstring_literals"); | |||
3554 | ||||
3555 | // String. | |||
3556 | llvm::Constant *Str = | |||
3557 | llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); | |||
3558 | ||||
3559 | if (isUTF16) | |||
3560 | // Cast the UTF16 string to the correct type. | |||
3561 | Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy); | |||
3562 | Fields.add(Str); | |||
3563 | ||||
3564 | // String length. | |||
3565 | auto Ty = getTypes().ConvertType(getContext().LongTy); | |||
3566 | Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength); | |||
3567 | ||||
3568 | CharUnits Alignment = getPointerAlign(); | |||
3569 | ||||
3570 | // The struct. | |||
3571 | GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment, | |||
3572 | /*isConstant=*/false, | |||
3573 | llvm::GlobalVariable::PrivateLinkage); | |||
3574 | switch (getTriple().getObjectFormat()) { | |||
3575 | case llvm::Triple::UnknownObjectFormat: | |||
3576 | llvm_unreachable("unknown file format")::llvm::llvm_unreachable_internal("unknown file format", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 3576); | |||
3577 | case llvm::Triple::COFF: | |||
3578 | case llvm::Triple::ELF: | |||
3579 | case llvm::Triple::Wasm: | |||
3580 | GV->setSection("cfstring"); | |||
3581 | break; | |||
3582 | case llvm::Triple::MachO: | |||
3583 | GV->setSection("__DATA,__cfstring"); | |||
3584 | break; | |||
3585 | } | |||
3586 | Entry.second = GV; | |||
3587 | ||||
3588 | return ConstantAddress(GV, Alignment); | |||
3589 | } | |||
3590 | ||||
3591 | bool CodeGenModule::getExpressionLocationsEnabled() const { | |||
3592 | return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo; | |||
3593 | } | |||
3594 | ||||
3595 | QualType CodeGenModule::getObjCFastEnumerationStateType() { | |||
3596 | if (ObjCFastEnumerationStateType.isNull()) { | |||
3597 | RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); | |||
3598 | D->startDefinition(); | |||
3599 | ||||
3600 | QualType FieldTypes[] = { | |||
3601 | Context.UnsignedLongTy, | |||
3602 | Context.getPointerType(Context.getObjCIdType()), | |||
3603 | Context.getPointerType(Context.UnsignedLongTy), | |||
3604 | Context.getConstantArrayType(Context.UnsignedLongTy, | |||
3605 | llvm::APInt(32, 5), ArrayType::Normal, 0) | |||
3606 | }; | |||
3607 | ||||
3608 | for (size_t i = 0; i < 4; ++i) { | |||
3609 | FieldDecl *Field = FieldDecl::Create(Context, | |||
3610 | D, | |||
3611 | SourceLocation(), | |||
3612 | SourceLocation(), nullptr, | |||
3613 | FieldTypes[i], /*TInfo=*/nullptr, | |||
3614 | /*BitWidth=*/nullptr, | |||
3615 | /*Mutable=*/false, | |||
3616 | ICIS_NoInit); | |||
3617 | Field->setAccess(AS_public); | |||
3618 | D->addDecl(Field); | |||
3619 | } | |||
3620 | ||||
3621 | D->completeDefinition(); | |||
3622 | ObjCFastEnumerationStateType = Context.getTagDeclType(D); | |||
3623 | } | |||
3624 | ||||
3625 | return ObjCFastEnumerationStateType; | |||
3626 | } | |||
3627 | ||||
3628 | llvm::Constant * | |||
3629 | CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { | |||
3630 | assert(!E->getType()->isPointerType() && "Strings are always arrays")(static_cast <bool> (!E->getType()->isPointerType () && "Strings are always arrays") ? void (0) : __assert_fail ("!E->getType()->isPointerType() && \"Strings are always arrays\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 3630, __extension__ __PRETTY_FUNCTION__)); | |||
3631 | ||||
3632 | // Don't emit it as the address of the string, emit the string data itself | |||
3633 | // as an inline array. | |||
3634 | if (E->getCharByteWidth() == 1) { | |||
3635 | SmallString<64> Str(E->getString()); | |||
3636 | ||||
3637 | // Resize the string to the right size, which is indicated by its type. | |||
3638 | const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); | |||
3639 | Str.resize(CAT->getSize().getZExtValue()); | |||
3640 | return llvm::ConstantDataArray::getString(VMContext, Str, false); | |||
3641 | } | |||
3642 | ||||
3643 | auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); | |||
3644 | llvm::Type *ElemTy = AType->getElementType(); | |||
3645 | unsigned NumElements = AType->getNumElements(); | |||
3646 | ||||
3647 | // Wide strings have either 2-byte or 4-byte elements. | |||
3648 | if (ElemTy->getPrimitiveSizeInBits() == 16) { | |||
3649 | SmallVector<uint16_t, 32> Elements; | |||
3650 | Elements.reserve(NumElements); | |||
3651 | ||||
3652 | for(unsigned i = 0, e = E->getLength(); i != e; ++i) | |||
3653 | Elements.push_back(E->getCodeUnit(i)); | |||
3654 | Elements.resize(NumElements); | |||
3655 | return llvm::ConstantDataArray::get(VMContext, Elements); | |||
3656 | } | |||
3657 | ||||
3658 | assert(ElemTy->getPrimitiveSizeInBits() == 32)(static_cast <bool> (ElemTy->getPrimitiveSizeInBits( ) == 32) ? void (0) : __assert_fail ("ElemTy->getPrimitiveSizeInBits() == 32" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 3658, __extension__ __PRETTY_FUNCTION__)); | |||
3659 | SmallVector<uint32_t, 32> Elements; | |||
3660 | Elements.reserve(NumElements); | |||
3661 | ||||
3662 | for(unsigned i = 0, e = E->getLength(); i != e; ++i) | |||
3663 | Elements.push_back(E->getCodeUnit(i)); | |||
3664 | Elements.resize(NumElements); | |||
3665 | return llvm::ConstantDataArray::get(VMContext, Elements); | |||
3666 | } | |||
3667 | ||||
3668 | static llvm::GlobalVariable * | |||
3669 | GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, | |||
3670 | CodeGenModule &CGM, StringRef GlobalName, | |||
3671 | CharUnits Alignment) { | |||
3672 | // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. | |||
3673 | unsigned AddrSpace = 0; | |||
3674 | if (CGM.getLangOpts().OpenCL) | |||
3675 | AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant); | |||
3676 | ||||
3677 | llvm::Module &M = CGM.getModule(); | |||
3678 | // Create a global variable for this string | |||
3679 | auto *GV = new llvm::GlobalVariable( | |||
3680 | M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, | |||
3681 | nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); | |||
3682 | GV->setAlignment(Alignment.getQuantity()); | |||
3683 | GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); | |||
3684 | if (GV->isWeakForLinker()) { | |||
3685 | assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals")(static_cast <bool> (CGM.supportsCOMDAT() && "Only COFF uses weak string literals" ) ? void (0) : __assert_fail ("CGM.supportsCOMDAT() && \"Only COFF uses weak string literals\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 3685, __extension__ __PRETTY_FUNCTION__)); | |||
3686 | GV->setComdat(M.getOrInsertComdat(GV->getName())); | |||
3687 | } | |||
3688 | ||||
3689 | return GV; | |||
3690 | } | |||
3691 | ||||
3692 | /// GetAddrOfConstantStringFromLiteral - Return a pointer to a | |||
3693 | /// constant array for the given string literal. | |||
3694 | ConstantAddress | |||
3695 | CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, | |||
3696 | StringRef Name) { | |||
3697 | CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType()); | |||
3698 | ||||
3699 | llvm::Constant *C = GetConstantArrayFromStringLiteral(S); | |||
3700 | llvm::GlobalVariable **Entry = nullptr; | |||
3701 | if (!LangOpts.WritableStrings) { | |||
3702 | Entry = &ConstantStringMap[C]; | |||
3703 | if (auto GV = *Entry) { | |||
3704 | if (Alignment.getQuantity() > GV->getAlignment()) | |||
3705 | GV->setAlignment(Alignment.getQuantity()); | |||
3706 | return ConstantAddress(GV, Alignment); | |||
3707 | } | |||
3708 | } | |||
3709 | ||||
3710 | SmallString<256> MangledNameBuffer; | |||
3711 | StringRef GlobalVariableName; | |||
3712 | llvm::GlobalValue::LinkageTypes LT; | |||
3713 | ||||
3714 | // Mangle the string literal if the ABI allows for it. However, we cannot | |||
3715 | // do this if we are compiling with ASan or -fwritable-strings because they | |||
3716 | // rely on strings having normal linkage. | |||
3717 | if (!LangOpts.WritableStrings && | |||
3718 | !LangOpts.Sanitize.has(SanitizerKind::Address) && | |||
3719 | getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) { | |||
3720 | llvm::raw_svector_ostream Out(MangledNameBuffer); | |||
3721 | getCXXABI().getMangleContext().mangleStringLiteral(S, Out); | |||
3722 | ||||
3723 | LT = llvm::GlobalValue::LinkOnceODRLinkage; | |||
3724 | GlobalVariableName = MangledNameBuffer; | |||
3725 | } else { | |||
3726 | LT = llvm::GlobalValue::PrivateLinkage; | |||
3727 | GlobalVariableName = Name; | |||
3728 | } | |||
3729 | ||||
3730 | auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); | |||
3731 | if (Entry) | |||
3732 | *Entry = GV; | |||
3733 | ||||
3734 | SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>", | |||
3735 | QualType()); | |||
3736 | return ConstantAddress(GV, Alignment); | |||
3737 | } | |||
3738 | ||||
3739 | /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant | |||
3740 | /// array for the given ObjCEncodeExpr node. | |||
3741 | ConstantAddress | |||
3742 | CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { | |||
3743 | std::string Str; | |||
3744 | getContext().getObjCEncodingForType(E->getEncodedType(), Str); | |||
3745 | ||||
3746 | return GetAddrOfConstantCString(Str); | |||
3747 | } | |||
3748 | ||||
3749 | /// GetAddrOfConstantCString - Returns a pointer to a character array containing | |||
3750 | /// the literal and a terminating '\0' character. | |||
3751 | /// The result has pointer to array type. | |||
3752 | ConstantAddress CodeGenModule::GetAddrOfConstantCString( | |||
3753 | const std::string &Str, const char *GlobalName) { | |||
3754 | StringRef StrWithNull(Str.c_str(), Str.size() + 1); | |||
3755 | CharUnits Alignment = | |||
3756 | getContext().getAlignOfGlobalVarInChars(getContext().CharTy); | |||
3757 | ||||
3758 | llvm::Constant *C = | |||
3759 | llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); | |||
3760 | ||||
3761 | // Don't share any string literals if strings aren't constant. | |||
3762 | llvm::GlobalVariable **Entry = nullptr; | |||
3763 | if (!LangOpts.WritableStrings) { | |||
3764 | Entry = &ConstantStringMap[C]; | |||
3765 | if (auto GV = *Entry) { | |||
3766 | if (Alignment.getQuantity() > GV->getAlignment()) | |||
3767 | GV->setAlignment(Alignment.getQuantity()); | |||
3768 | return ConstantAddress(GV, Alignment); | |||
3769 | } | |||
3770 | } | |||
3771 | ||||
3772 | // Get the default prefix if a name wasn't specified. | |||
3773 | if (!GlobalName) | |||
3774 | GlobalName = ".str"; | |||
3775 | // Create a global variable for this. | |||
3776 | auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, | |||
3777 | GlobalName, Alignment); | |||
3778 | if (Entry) | |||
3779 | *Entry = GV; | |||
3780 | return ConstantAddress(GV, Alignment); | |||
3781 | } | |||
3782 | ||||
3783 | ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( | |||
3784 | const MaterializeTemporaryExpr *E, const Expr *Init) { | |||
3785 | assert((E->getStorageDuration() == SD_Static ||(static_cast <bool> ((E->getStorageDuration() == SD_Static || E->getStorageDuration() == SD_Thread) && "not a global temporary" ) ? void (0) : __assert_fail ("(E->getStorageDuration() == SD_Static || E->getStorageDuration() == SD_Thread) && \"not a global temporary\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 3786, __extension__ __PRETTY_FUNCTION__)) | |||
3786 | E->getStorageDuration() == SD_Thread) && "not a global temporary")(static_cast <bool> ((E->getStorageDuration() == SD_Static || E->getStorageDuration() == SD_Thread) && "not a global temporary" ) ? void (0) : __assert_fail ("(E->getStorageDuration() == SD_Static || E->getStorageDuration() == SD_Thread) && \"not a global temporary\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 3786, __extension__ __PRETTY_FUNCTION__)); | |||
3787 | const auto *VD = cast<VarDecl>(E->getExtendingDecl()); | |||
| ||||
3788 | ||||
3789 | // If we're not materializing a subobject of the temporary, keep the | |||
3790 | // cv-qualifiers from the type of the MaterializeTemporaryExpr. | |||
3791 | QualType MaterializedType = Init->getType(); | |||
3792 | if (Init == E->GetTemporaryExpr()) | |||
3793 | MaterializedType = E->getType(); | |||
3794 | ||||
3795 | CharUnits Align = getContext().getTypeAlignInChars(MaterializedType); | |||
3796 | ||||
3797 | if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E]) | |||
3798 | return ConstantAddress(Slot, Align); | |||
3799 | ||||
3800 | // FIXME: If an externally-visible declaration extends multiple temporaries, | |||
3801 | // we need to give each temporary the same name in every translation unit (and | |||
3802 | // we also need to make the temporaries externally-visible). | |||
3803 | SmallString<256> Name; | |||
3804 | llvm::raw_svector_ostream Out(Name); | |||
3805 | getCXXABI().getMangleContext().mangleReferenceTemporary( | |||
3806 | VD, E->getManglingNumber(), Out); | |||
3807 | ||||
3808 | APValue *Value = nullptr; | |||
3809 | if (E->getStorageDuration() == SD_Static) { | |||
3810 | // We might have a cached constant initializer for this temporary. Note | |||
3811 | // that this might have a different value from the value computed by | |||
3812 | // evaluating the initializer if the surrounding constant expression | |||
3813 | // modifies the temporary. | |||
3814 | Value = getContext().getMaterializedTemporaryValue(E, false); | |||
3815 | if (Value && Value->isUninit()) | |||
3816 | Value = nullptr; | |||
3817 | } | |||
3818 | ||||
3819 | // Try evaluating it now, it might have a constant initializer. | |||
3820 | Expr::EvalResult EvalResult; | |||
3821 | if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && | |||
3822 | !EvalResult.hasSideEffects()) | |||
3823 | Value = &EvalResult.Val; | |||
3824 | ||||
3825 | LangAS AddrSpace = | |||
3826 | VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace(); | |||
3827 | ||||
3828 | Optional<ConstantEmitter> emitter; | |||
3829 | llvm::Constant *InitialValue = nullptr; | |||
3830 | bool Constant = false; | |||
3831 | llvm::Type *Type; | |||
3832 | if (Value) { | |||
3833 | // The temporary has a constant initializer, use it. | |||
3834 | emitter.emplace(*this); | |||
3835 | InitialValue = emitter->emitForInitializer(*Value, AddrSpace, | |||
3836 | MaterializedType); | |||
3837 | Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); | |||
3838 | Type = InitialValue->getType(); | |||
3839 | } else { | |||
3840 | // No initializer, the initialization will be provided when we | |||
3841 | // initialize the declaration which performed lifetime extension. | |||
3842 | Type = getTypes().ConvertTypeForMem(MaterializedType); | |||
3843 | } | |||
3844 | ||||
3845 | // Create a global variable for this lifetime-extended temporary. | |||
3846 | llvm::GlobalValue::LinkageTypes Linkage = | |||
3847 | getLLVMLinkageVarDefinition(VD, Constant); | |||
3848 | if (Linkage == llvm::GlobalVariable::ExternalLinkage) { | |||
3849 | const VarDecl *InitVD; | |||
3850 | if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) && | |||
3851 | isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { | |||
3852 | // Temporaries defined inside a class get linkonce_odr linkage because the | |||
3853 | // class can be defined in multipe translation units. | |||
3854 | Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; | |||
3855 | } else { | |||
3856 | // There is no need for this temporary to have external linkage if the | |||
3857 | // VarDecl has external linkage. | |||
3858 | Linkage = llvm::GlobalVariable::InternalLinkage; | |||
3859 | } | |||
3860 | } | |||
3861 | auto TargetAS = getContext().getTargetAddressSpace(AddrSpace); | |||
3862 | auto *GV = new llvm::GlobalVariable( | |||
3863 | getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), | |||
3864 | /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS); | |||
3865 | if (emitter) emitter->finalize(GV); | |||
3866 | setGlobalVisibility(GV, VD, ForDefinition); | |||
3867 | GV->setAlignment(Align.getQuantity()); | |||
3868 | if (supportsCOMDAT() && GV->isWeakForLinker()) | |||
3869 | GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); | |||
3870 | if (VD->getTLSKind()) | |||
3871 | setTLSMode(GV, *VD); | |||
3872 | llvm::Constant *CV = GV; | |||
3873 | if (AddrSpace != LangAS::Default) | |||
3874 | CV = getTargetCodeGenInfo().performAddrSpaceCast( | |||
3875 | *this, GV, AddrSpace, LangAS::Default, | |||
3876 | Type->getPointerTo( | |||
3877 | getContext().getTargetAddressSpace(LangAS::Default))); | |||
3878 | MaterializedGlobalTemporaryMap[E] = CV; | |||
3879 | return ConstantAddress(CV, Align); | |||
3880 | } | |||
3881 | ||||
3882 | /// EmitObjCPropertyImplementations - Emit information for synthesized | |||
3883 | /// properties for an implementation. | |||
3884 | void CodeGenModule::EmitObjCPropertyImplementations(const | |||
3885 | ObjCImplementationDecl *D) { | |||
3886 | for (const auto *PID : D->property_impls()) { | |||
3887 | // Dynamic is just for type-checking. | |||
3888 | if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { | |||
3889 | ObjCPropertyDecl *PD = PID->getPropertyDecl(); | |||
3890 | ||||
3891 | // Determine which methods need to be implemented, some may have | |||
3892 | // been overridden. Note that ::isPropertyAccessor is not the method | |||
3893 | // we want, that just indicates if the decl came from a | |||
3894 | // property. What we want to know is if the method is defined in | |||
3895 | // this implementation. | |||
3896 | if (!D->getInstanceMethod(PD->getGetterName())) | |||
3897 | CodeGenFunction(*this).GenerateObjCGetter( | |||
3898 | const_cast<ObjCImplementationDecl *>(D), PID); | |||
3899 | if (!PD->isReadOnly() && | |||
3900 | !D->getInstanceMethod(PD->getSetterName())) | |||
3901 | CodeGenFunction(*this).GenerateObjCSetter( | |||
3902 | const_cast<ObjCImplementationDecl *>(D), PID); | |||
3903 | } | |||
3904 | } | |||
3905 | } | |||
3906 | ||||
3907 | static bool needsDestructMethod(ObjCImplementationDecl *impl) { | |||
3908 | const ObjCInterfaceDecl *iface = impl->getClassInterface(); | |||
3909 | for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); | |||
3910 | ivar; ivar = ivar->getNextIvar()) | |||
3911 | if (ivar->getType().isDestructedType()) | |||
3912 | return true; | |||
3913 | ||||
3914 | return false; | |||
3915 | } | |||
3916 | ||||
3917 | static bool AllTrivialInitializers(CodeGenModule &CGM, | |||
3918 | ObjCImplementationDecl *D) { | |||
3919 | CodeGenFunction CGF(CGM); | |||
3920 | for (ObjCImplementationDecl::init_iterator B = D->init_begin(), | |||
3921 | E = D->init_end(); B != E; ++B) { | |||
3922 | CXXCtorInitializer *CtorInitExp = *B; | |||
3923 | Expr *Init = CtorInitExp->getInit(); | |||
3924 | if (!CGF.isTrivialInitializer(Init)) | |||
3925 | return false; | |||
3926 | } | |||
3927 | return true; | |||
3928 | } | |||
3929 | ||||
3930 | /// EmitObjCIvarInitializations - Emit information for ivar initialization | |||
3931 | /// for an implementation. | |||
3932 | void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { | |||
3933 | // We might need a .cxx_destruct even if we don't have any ivar initializers. | |||
3934 | if (needsDestructMethod(D)) { | |||
3935 | IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); | |||
3936 | Selector cxxSelector = getContext().Selectors.getSelector(0, &II); | |||
3937 | ObjCMethodDecl *DTORMethod = | |||
3938 | ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(), | |||
3939 | cxxSelector, getContext().VoidTy, nullptr, D, | |||
3940 | /*isInstance=*/true, /*isVariadic=*/false, | |||
3941 | /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true, | |||
3942 | /*isDefined=*/false, ObjCMethodDecl::Required); | |||
3943 | D->addInstanceMethod(DTORMethod); | |||
3944 | CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); | |||
3945 | D->setHasDestructors(true); | |||
3946 | } | |||
3947 | ||||
3948 | // If the implementation doesn't have any ivar initializers, we don't need | |||
3949 | // a .cxx_construct. | |||
3950 | if (D->getNumIvarInitializers() == 0 || | |||
3951 | AllTrivialInitializers(*this, D)) | |||
3952 | return; | |||
3953 | ||||
3954 | IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); | |||
3955 | Selector cxxSelector = getContext().Selectors.getSelector(0, &II); | |||
3956 | // The constructor returns 'self'. | |||
3957 | ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), | |||
3958 | D->getLocation(), | |||
3959 | D->getLocation(), | |||
3960 | cxxSelector, | |||
3961 | getContext().getObjCIdType(), | |||
3962 | nullptr, D, /*isInstance=*/true, | |||
3963 | /*isVariadic=*/false, | |||
3964 | /*isPropertyAccessor=*/true, | |||
3965 | /*isImplicitlyDeclared=*/true, | |||
3966 | /*isDefined=*/false, | |||
3967 | ObjCMethodDecl::Required); | |||
3968 | D->addInstanceMethod(CTORMethod); | |||
3969 | CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); | |||
3970 | D->setHasNonZeroConstructors(true); | |||
3971 | } | |||
3972 | ||||
3973 | // EmitLinkageSpec - Emit all declarations in a linkage spec. | |||
3974 | void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { | |||
3975 | if (LSD->getLanguage() != LinkageSpecDecl::lang_c && | |||
3976 | LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { | |||
3977 | ErrorUnsupported(LSD, "linkage spec"); | |||
3978 | return; | |||
3979 | } | |||
3980 | ||||
3981 | EmitDeclContext(LSD); | |||
3982 | } | |||
3983 | ||||
3984 | void CodeGenModule::EmitDeclContext(const DeclContext *DC) { | |||
3985 | for (auto *I : DC->decls()) { | |||
3986 | // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope | |||
3987 | // are themselves considered "top-level", so EmitTopLevelDecl on an | |||
3988 | // ObjCImplDecl does not recursively visit them. We need to do that in | |||
3989 | // case they're nested inside another construct (LinkageSpecDecl / | |||
3990 | // ExportDecl) that does stop them from being considered "top-level". | |||
3991 | if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { | |||
3992 | for (auto *M : OID->methods()) | |||
3993 | EmitTopLevelDecl(M); | |||
3994 | } | |||
3995 | ||||
3996 | EmitTopLevelDecl(I); | |||
3997 | } | |||
3998 | } | |||
3999 | ||||
4000 | /// EmitTopLevelDecl - Emit code for a single top level declaration. | |||
4001 | void CodeGenModule::EmitTopLevelDecl(Decl *D) { | |||
4002 | // Ignore dependent declarations. | |||
4003 | if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) | |||
4004 | return; | |||
4005 | ||||
4006 | switch (D->getKind()) { | |||
4007 | case Decl::CXXConversion: | |||
4008 | case Decl::CXXMethod: | |||
4009 | case Decl::Function: | |||
4010 | // Skip function templates | |||
4011 | if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || | |||
4012 | cast<FunctionDecl>(D)->isLateTemplateParsed()) | |||
4013 | return; | |||
4014 | ||||
4015 | EmitGlobal(cast<FunctionDecl>(D)); | |||
4016 | // Always provide some coverage mapping | |||
4017 | // even for the functions that aren't emitted. | |||
4018 | AddDeferredUnusedCoverageMapping(D); | |||
4019 | break; | |||
4020 | ||||
4021 | case Decl::CXXDeductionGuide: | |||
4022 | // Function-like, but does not result in code emission. | |||
4023 | break; | |||
4024 | ||||
4025 | case Decl::Var: | |||
4026 | case Decl::Decomposition: | |||
4027 | // Skip variable templates | |||
4028 | if (cast<VarDecl>(D)->getDescribedVarTemplate()) | |||
4029 | return; | |||
4030 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
4031 | case Decl::VarTemplateSpecialization: | |||
4032 | EmitGlobal(cast<VarDecl>(D)); | |||
4033 | if (auto *DD = dyn_cast<DecompositionDecl>(D)) | |||
4034 | for (auto *B : DD->bindings()) | |||
4035 | if (auto *HD = B->getHoldingVar()) | |||
4036 | EmitGlobal(HD); | |||
4037 | break; | |||
4038 | ||||
4039 | // Indirect fields from global anonymous structs and unions can be | |||
4040 | // ignored; only the actual variable requires IR gen support. | |||
4041 | case Decl::IndirectField: | |||
4042 | break; | |||
4043 | ||||
4044 | // C++ Decls | |||
4045 | case Decl::Namespace: | |||
4046 | EmitDeclContext(cast<NamespaceDecl>(D)); | |||
4047 | break; | |||
4048 | case Decl::ClassTemplateSpecialization: { | |||
4049 | const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); | |||
4050 | if (DebugInfo && | |||
4051 | Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition && | |||
4052 | Spec->hasDefinition()) | |||
4053 | DebugInfo->completeTemplateDefinition(*Spec); | |||
4054 | } LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
4055 | case Decl::CXXRecord: | |||
4056 | if (DebugInfo) { | |||
4057 | if (auto *ES = D->getASTContext().getExternalSource()) | |||
4058 | if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never) | |||
4059 | DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D)); | |||
4060 | } | |||
4061 | // Emit any static data members, they may be definitions. | |||
4062 | for (auto *I : cast<CXXRecordDecl>(D)->decls()) | |||
4063 | if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I)) | |||
4064 | EmitTopLevelDecl(I); | |||
4065 | break; | |||
4066 | // No code generation needed. | |||
4067 | case Decl::UsingShadow: | |||
4068 | case Decl::ClassTemplate: | |||
4069 | case Decl::VarTemplate: | |||
4070 | case Decl::VarTemplatePartialSpecialization: | |||
4071 | case Decl::FunctionTemplate: | |||
4072 | case Decl::TypeAliasTemplate: | |||
4073 | case Decl::Block: | |||
4074 | case Decl::Empty: | |||
4075 | break; | |||
4076 | case Decl::Using: // using X; [C++] | |||
4077 | if (CGDebugInfo *DI = getModuleDebugInfo()) | |||
4078 | DI->EmitUsingDecl(cast<UsingDecl>(*D)); | |||
4079 | return; | |||
4080 | case Decl::NamespaceAlias: | |||
4081 | if (CGDebugInfo *DI = getModuleDebugInfo()) | |||
4082 | DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); | |||
4083 | return; | |||
4084 | case Decl::UsingDirective: // using namespace X; [C++] | |||
4085 | if (CGDebugInfo *DI = getModuleDebugInfo()) | |||
4086 | DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); | |||
4087 | return; | |||
4088 | case Decl::CXXConstructor: | |||
4089 | // Skip function templates | |||
4090 | if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || | |||
4091 | cast<FunctionDecl>(D)->isLateTemplateParsed()) | |||
4092 | return; | |||
4093 | ||||
4094 | getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); | |||
4095 | break; | |||
4096 | case Decl::CXXDestructor: | |||
4097 | if (cast<FunctionDecl>(D)->isLateTemplateParsed()) | |||
4098 | return; | |||
4099 | getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); | |||
4100 | break; | |||
4101 | ||||
4102 | case Decl::StaticAssert: | |||
4103 | // Nothing to do. | |||
4104 | break; | |||
4105 | ||||
4106 | // Objective-C Decls | |||
4107 | ||||
4108 | // Forward declarations, no (immediate) code generation. | |||
4109 | case Decl::ObjCInterface: | |||
4110 | case Decl::ObjCCategory: | |||
4111 | break; | |||
4112 | ||||
4113 | case Decl::ObjCProtocol: { | |||
4114 | auto *Proto = cast<ObjCProtocolDecl>(D); | |||
4115 | if (Proto->isThisDeclarationADefinition()) | |||
4116 | ObjCRuntime->GenerateProtocol(Proto); | |||
4117 | break; | |||
4118 | } | |||
4119 | ||||
4120 | case Decl::ObjCCategoryImpl: | |||
4121 | // Categories have properties but don't support synthesize so we | |||
4122 | // can ignore them here. | |||
4123 | ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); | |||
4124 | break; | |||
4125 | ||||
4126 | case Decl::ObjCImplementation: { | |||
4127 | auto *OMD = cast<ObjCImplementationDecl>(D); | |||
4128 | EmitObjCPropertyImplementations(OMD); | |||
4129 | EmitObjCIvarInitializations(OMD); | |||
4130 | ObjCRuntime->GenerateClass(OMD); | |||
4131 | // Emit global variable debug information. | |||
4132 | if (CGDebugInfo *DI = getModuleDebugInfo()) | |||
4133 | if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) | |||
4134 | DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( | |||
4135 | OMD->getClassInterface()), OMD->getLocation()); | |||
4136 | break; | |||
4137 | } | |||
4138 | case Decl::ObjCMethod: { | |||
4139 | auto *OMD = cast<ObjCMethodDecl>(D); | |||
4140 | // If this is not a prototype, emit the body. | |||
4141 | if (OMD->getBody()) | |||
4142 | CodeGenFunction(*this).GenerateObjCMethod(OMD); | |||
4143 | break; | |||
4144 | } | |||
4145 | case Decl::ObjCCompatibleAlias: | |||
4146 | ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); | |||
4147 | break; | |||
4148 | ||||
4149 | case Decl::PragmaComment: { | |||
4150 | const auto *PCD = cast<PragmaCommentDecl>(D); | |||
4151 | switch (PCD->getCommentKind()) { | |||
4152 | case PCK_Unknown: | |||
4153 | llvm_unreachable("unexpected pragma comment kind")::llvm::llvm_unreachable_internal("unexpected pragma comment kind" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 4153); | |||
4154 | case PCK_Linker: | |||
4155 | AppendLinkerOptions(PCD->getArg()); | |||
4156 | break; | |||
4157 | case PCK_Lib: | |||
4158 | AddDependentLib(PCD->getArg()); | |||
4159 | break; | |||
4160 | case PCK_Compiler: | |||
4161 | case PCK_ExeStr: | |||
4162 | case PCK_User: | |||
4163 | break; // We ignore all of these. | |||
4164 | } | |||
4165 | break; | |||
4166 | } | |||
4167 | ||||
4168 | case Decl::PragmaDetectMismatch: { | |||
4169 | const auto *PDMD = cast<PragmaDetectMismatchDecl>(D); | |||
4170 | AddDetectMismatch(PDMD->getName(), PDMD->getValue()); | |||
4171 | break; | |||
4172 | } | |||
4173 | ||||
4174 | case Decl::LinkageSpec: | |||
4175 | EmitLinkageSpec(cast<LinkageSpecDecl>(D)); | |||
4176 | break; | |||
4177 | ||||
4178 | case Decl::FileScopeAsm: { | |||
4179 | // File-scope asm is ignored during device-side CUDA compilation. | |||
4180 | if (LangOpts.CUDA && LangOpts.CUDAIsDevice) | |||
4181 | break; | |||
4182 | // File-scope asm is ignored during device-side OpenMP compilation. | |||
4183 | if (LangOpts.OpenMPIsDevice) | |||
4184 | break; | |||
4185 | auto *AD = cast<FileScopeAsmDecl>(D); | |||
4186 | getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); | |||
4187 | break; | |||
4188 | } | |||
4189 | ||||
4190 | case Decl::Import: { | |||
4191 | auto *Import = cast<ImportDecl>(D); | |||
4192 | ||||
4193 | // If we've already imported this module, we're done. | |||
4194 | if (!ImportedModules.insert(Import->getImportedModule())) | |||
4195 | break; | |||
4196 | ||||
4197 | // Emit debug information for direct imports. | |||
4198 | if (!Import->getImportedOwningModule()) { | |||
4199 | if (CGDebugInfo *DI = getModuleDebugInfo()) | |||
4200 | DI->EmitImportDecl(*Import); | |||
4201 | } | |||
4202 | ||||
4203 | // Find all of the submodules and emit the module initializers. | |||
4204 | llvm::SmallPtrSet<clang::Module *, 16> Visited; | |||
4205 | SmallVector<clang::Module *, 16> Stack; | |||
4206 | Visited.insert(Import->getImportedModule()); | |||
4207 | Stack.push_back(Import->getImportedModule()); | |||
4208 | ||||
4209 | while (!Stack.empty()) { | |||
4210 | clang::Module *Mod = Stack.pop_back_val(); | |||
4211 | if (!EmittedModuleInitializers.insert(Mod).second) | |||
4212 | continue; | |||
4213 | ||||
4214 | for (auto *D : Context.getModuleInitializers(Mod)) | |||
4215 | EmitTopLevelDecl(D); | |||
4216 | ||||
4217 | // Visit the submodules of this module. | |||
4218 | for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), | |||
4219 | SubEnd = Mod->submodule_end(); | |||
4220 | Sub != SubEnd; ++Sub) { | |||
4221 | // Skip explicit children; they need to be explicitly imported to emit | |||
4222 | // the initializers. | |||
4223 | if ((*Sub)->IsExplicit) | |||
4224 | continue; | |||
4225 | ||||
4226 | if (Visited.insert(*Sub).second) | |||
4227 | Stack.push_back(*Sub); | |||
4228 | } | |||
4229 | } | |||
4230 | break; | |||
4231 | } | |||
4232 | ||||
4233 | case Decl::Export: | |||
4234 | EmitDeclContext(cast<ExportDecl>(D)); | |||
4235 | break; | |||
4236 | ||||
4237 | case Decl::OMPThreadPrivate: | |||
4238 | EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); | |||
4239 | break; | |||
4240 | ||||
4241 | case Decl::OMPDeclareReduction: | |||
4242 | EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D)); | |||
4243 | break; | |||
4244 | ||||
4245 | default: | |||
4246 | // Make sure we handled everything we should, every other kind is a | |||
4247 | // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind | |||
4248 | // function. Need to recode Decl::Kind to do that easily. | |||
4249 | assert(isa<TypeDecl>(D) && "Unsupported decl kind")(static_cast <bool> (isa<TypeDecl>(D) && "Unsupported decl kind" ) ? void (0) : __assert_fail ("isa<TypeDecl>(D) && \"Unsupported decl kind\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 4249, __extension__ __PRETTY_FUNCTION__)); | |||
4250 | break; | |||
4251 | } | |||
4252 | } | |||
4253 | ||||
4254 | void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { | |||
4255 | // Do we need to generate coverage mapping? | |||
4256 | if (!CodeGenOpts.CoverageMapping) | |||
4257 | return; | |||
4258 | switch (D->getKind()) { | |||
4259 | case Decl::CXXConversion: | |||
4260 | case Decl::CXXMethod: | |||
4261 | case Decl::Function: | |||
4262 | case Decl::ObjCMethod: | |||
4263 | case Decl::CXXConstructor: | |||
4264 | case Decl::CXXDestructor: { | |||
4265 | if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) | |||
4266 | return; | |||
4267 | SourceManager &SM = getContext().getSourceManager(); | |||
4268 | if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getLocStart())) | |||
4269 | return; | |||
4270 | auto I = DeferredEmptyCoverageMappingDecls.find(D); | |||
4271 | if (I == DeferredEmptyCoverageMappingDecls.end()) | |||
4272 | DeferredEmptyCoverageMappingDecls[D] = true; | |||
4273 | break; | |||
4274 | } | |||
4275 | default: | |||
4276 | break; | |||
4277 | }; | |||
4278 | } | |||
4279 | ||||
4280 | void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { | |||
4281 | // Do we need to generate coverage mapping? | |||
4282 | if (!CodeGenOpts.CoverageMapping) | |||
4283 | return; | |||
4284 | if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { | |||
4285 | if (Fn->isTemplateInstantiation()) | |||
4286 | ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); | |||
4287 | } | |||
4288 | auto I = DeferredEmptyCoverageMappingDecls.find(D); | |||
4289 | if (I == DeferredEmptyCoverageMappingDecls.end()) | |||
4290 | DeferredEmptyCoverageMappingDecls[D] = false; | |||
4291 | else | |||
4292 | I->second = false; | |||
4293 | } | |||
4294 | ||||
4295 | void CodeGenModule::EmitDeferredUnusedCoverageMappings() { | |||
4296 | // We call takeVector() here to avoid use-after-free. | |||
4297 | // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because | |||
4298 | // we deserialize function bodies to emit coverage info for them, and that | |||
4299 | // deserializes more declarations. How should we handle that case? | |||
4300 | for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) { | |||
4301 | if (!Entry.second) | |||
4302 | continue; | |||
4303 | const Decl *D = Entry.first; | |||
4304 | switch (D->getKind()) { | |||
4305 | case Decl::CXXConversion: | |||
4306 | case Decl::CXXMethod: | |||
4307 | case Decl::Function: | |||
4308 | case Decl::ObjCMethod: { | |||
4309 | CodeGenPGO PGO(*this); | |||
4310 | GlobalDecl GD(cast<FunctionDecl>(D)); | |||
4311 | PGO.emitEmptyCounterMapping(D, getMangledName(GD), | |||
4312 | getFunctionLinkage(GD)); | |||
4313 | break; | |||
4314 | } | |||
4315 | case Decl::CXXConstructor: { | |||
4316 | CodeGenPGO PGO(*this); | |||
4317 | GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); | |||
4318 | PGO.emitEmptyCounterMapping(D, getMangledName(GD), | |||
4319 | getFunctionLinkage(GD)); | |||
4320 | break; | |||
4321 | } | |||
4322 | case Decl::CXXDestructor: { | |||
4323 | CodeGenPGO PGO(*this); | |||
4324 | GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); | |||
4325 | PGO.emitEmptyCounterMapping(D, getMangledName(GD), | |||
4326 | getFunctionLinkage(GD)); | |||
4327 | break; | |||
4328 | } | |||
4329 | default: | |||
4330 | break; | |||
4331 | }; | |||
4332 | } | |||
4333 | } | |||
4334 | ||||
4335 | /// Turns the given pointer into a constant. | |||
4336 | static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, | |||
4337 | const void *Ptr) { | |||
4338 | uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); | |||
4339 | llvm::Type *i64 = llvm::Type::getInt64Ty(Context); | |||
4340 | return llvm::ConstantInt::get(i64, PtrInt); | |||
4341 | } | |||
4342 | ||||
4343 | static void EmitGlobalDeclMetadata(CodeGenModule &CGM, | |||
4344 | llvm::NamedMDNode *&GlobalMetadata, | |||
4345 | GlobalDecl D, | |||
4346 | llvm::GlobalValue *Addr) { | |||
4347 | if (!GlobalMetadata) | |||
4348 | GlobalMetadata = | |||
4349 | CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); | |||
4350 | ||||
4351 | // TODO: should we report variant information for ctors/dtors? | |||
4352 | llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), | |||
4353 | llvm::ConstantAsMetadata::get(GetPointerConstant( | |||
4354 | CGM.getLLVMContext(), D.getDecl()))}; | |||
4355 | GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); | |||
4356 | } | |||
4357 | ||||
4358 | /// For each function which is declared within an extern "C" region and marked | |||
4359 | /// as 'used', but has internal linkage, create an alias from the unmangled | |||
4360 | /// name to the mangled name if possible. People expect to be able to refer | |||
4361 | /// to such functions with an unmangled name from inline assembly within the | |||
4362 | /// same translation unit. | |||
4363 | void CodeGenModule::EmitStaticExternCAliases() { | |||
4364 | // Don't do anything if we're generating CUDA device code -- the NVPTX | |||
4365 | // assembly target doesn't support aliases. | |||
4366 | if (Context.getTargetInfo().getTriple().isNVPTX()) | |||
4367 | return; | |||
4368 | for (auto &I : StaticExternCValues) { | |||
4369 | IdentifierInfo *Name = I.first; | |||
4370 | llvm::GlobalValue *Val = I.second; | |||
4371 | if (Val && !getModule().getNamedValue(Name->getName())) | |||
4372 | addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); | |||
4373 | } | |||
4374 | } | |||
4375 | ||||
4376 | bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, | |||
4377 | GlobalDecl &Result) const { | |||
4378 | auto Res = Manglings.find(MangledName); | |||
4379 | if (Res == Manglings.end()) | |||
4380 | return false; | |||
4381 | Result = Res->getValue(); | |||
4382 | return true; | |||
4383 | } | |||
4384 | ||||
4385 | /// Emits metadata nodes associating all the global values in the | |||
4386 | /// current module with the Decls they came from. This is useful for | |||
4387 | /// projects using IR gen as a subroutine. | |||
4388 | /// | |||
4389 | /// Since there's currently no way to associate an MDNode directly | |||
4390 | /// with an llvm::GlobalValue, we create a global named metadata | |||
4391 | /// with the name 'clang.global.decl.ptrs'. | |||
4392 | void CodeGenModule::EmitDeclMetadata() { | |||
4393 | llvm::NamedMDNode *GlobalMetadata = nullptr; | |||
4394 | ||||
4395 | for (auto &I : MangledDeclNames) { | |||
4396 | llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); | |||
4397 | // Some mangled names don't necessarily have an associated GlobalValue | |||
4398 | // in this module, e.g. if we mangled it for DebugInfo. | |||
4399 | if (Addr) | |||
4400 | EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); | |||
4401 | } | |||
4402 | } | |||
4403 | ||||
4404 | /// Emits metadata nodes for all the local variables in the current | |||
4405 | /// function. | |||
4406 | void CodeGenFunction::EmitDeclMetadata() { | |||
4407 | if (LocalDeclMap.empty()) return; | |||
4408 | ||||
4409 | llvm::LLVMContext &Context = getLLVMContext(); | |||
4410 | ||||
4411 | // Find the unique metadata ID for this name. | |||
4412 | unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); | |||
4413 | ||||
4414 | llvm::NamedMDNode *GlobalMetadata = nullptr; | |||
4415 | ||||
4416 | for (auto &I : LocalDeclMap) { | |||
4417 | const Decl *D = I.first; | |||
4418 | llvm::Value *Addr = I.second.getPointer(); | |||
4419 | if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { | |||
4420 | llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); | |||
4421 | Alloca->setMetadata( | |||
4422 | DeclPtrKind, llvm::MDNode::get( | |||
4423 | Context, llvm::ValueAsMetadata::getConstant(DAddr))); | |||
4424 | } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { | |||
4425 | GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); | |||
4426 | EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); | |||
4427 | } | |||
4428 | } | |||
4429 | } | |||
4430 | ||||
4431 | void CodeGenModule::EmitVersionIdentMetadata() { | |||
4432 | llvm::NamedMDNode *IdentMetadata = | |||
4433 | TheModule.getOrInsertNamedMetadata("llvm.ident"); | |||
4434 | std::string Version = getClangFullVersion(); | |||
4435 | llvm::LLVMContext &Ctx = TheModule.getContext(); | |||
4436 | ||||
4437 | llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; | |||
4438 | IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); | |||
4439 | } | |||
4440 | ||||
4441 | void CodeGenModule::EmitTargetMetadata() { | |||
4442 | // Warning, new MangledDeclNames may be appended within this loop. | |||
4443 | // We rely on MapVector insertions adding new elements to the end | |||
4444 | // of the container. | |||
4445 | // FIXME: Move this loop into the one target that needs it, and only | |||
4446 | // loop over those declarations for which we couldn't emit the target | |||
4447 | // metadata when we emitted the declaration. | |||
4448 | for (unsigned I = 0; I != MangledDeclNames.size(); ++I) { | |||
4449 | auto Val = *(MangledDeclNames.begin() + I); | |||
4450 | const Decl *D = Val.first.getDecl()->getMostRecentDecl(); | |||
4451 | llvm::GlobalValue *GV = GetGlobalValue(Val.second); | |||
4452 | getTargetCodeGenInfo().emitTargetMD(D, GV, *this); | |||
4453 | } | |||
4454 | } | |||
4455 | ||||
4456 | void CodeGenModule::EmitCoverageFile() { | |||
4457 | if (getCodeGenOpts().CoverageDataFile.empty() && | |||
4458 | getCodeGenOpts().CoverageNotesFile.empty()) | |||
4459 | return; | |||
4460 | ||||
4461 | llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu"); | |||
4462 | if (!CUNode) | |||
4463 | return; | |||
4464 | ||||
4465 | llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); | |||
4466 | llvm::LLVMContext &Ctx = TheModule.getContext(); | |||
4467 | auto *CoverageDataFile = | |||
4468 | llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile); | |||
4469 | auto *CoverageNotesFile = | |||
4470 | llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile); | |||
4471 | for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { | |||
4472 | llvm::MDNode *CU = CUNode->getOperand(i); | |||
4473 | llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU}; | |||
4474 | GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); | |||
4475 | } | |||
4476 | } | |||
4477 | ||||
4478 | llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) { | |||
4479 | // Sema has checked that all uuid strings are of the form | |||
4480 | // "12345678-1234-1234-1234-1234567890ab". | |||
4481 | assert(Uuid.size() == 36)(static_cast <bool> (Uuid.size() == 36) ? void (0) : __assert_fail ("Uuid.size() == 36", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 4481, __extension__ __PRETTY_FUNCTION__)); | |||
4482 | for (unsigned i = 0; i < 36; ++i) { | |||
4483 | if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-')(static_cast <bool> (Uuid[i] == '-') ? void (0) : __assert_fail ("Uuid[i] == '-'", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 4483, __extension__ __PRETTY_FUNCTION__)); | |||
4484 | else assert(isHexDigit(Uuid[i]))(static_cast <bool> (isHexDigit(Uuid[i])) ? void (0) : __assert_fail ("isHexDigit(Uuid[i])", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 4484, __extension__ __PRETTY_FUNCTION__)); | |||
4485 | } | |||
4486 | ||||
4487 | // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab". | |||
4488 | const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 }; | |||
4489 | ||||
4490 | llvm::Constant *Field3[8]; | |||
4491 | for (unsigned Idx = 0; Idx < 8; ++Idx) | |||
4492 | Field3[Idx] = llvm::ConstantInt::get( | |||
4493 | Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16); | |||
4494 | ||||
4495 | llvm::Constant *Fields[4] = { | |||
4496 | llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16), | |||
4497 | llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16), | |||
4498 | llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16), | |||
4499 | llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3) | |||
4500 | }; | |||
4501 | ||||
4502 | return llvm::ConstantStruct::getAnon(Fields); | |||
4503 | } | |||
4504 | ||||
4505 | llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, | |||
4506 | bool ForEH) { | |||
4507 | // Return a bogus pointer if RTTI is disabled, unless it's for EH. | |||
4508 | // FIXME: should we even be calling this method if RTTI is disabled | |||
4509 | // and it's not for EH? | |||
4510 | if (!ForEH && !getLangOpts().RTTI) | |||
4511 | return llvm::Constant::getNullValue(Int8PtrTy); | |||
4512 | ||||
4513 | if (ForEH && Ty->isObjCObjectPointerType() && | |||
4514 | LangOpts.ObjCRuntime.isGNUFamily()) | |||
4515 | return ObjCRuntime->GetEHType(Ty); | |||
4516 | ||||
4517 | return getCXXABI().getAddrOfRTTIDescriptor(Ty); | |||
4518 | } | |||
4519 | ||||
4520 | void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { | |||
4521 | // Do not emit threadprivates in simd-only mode. | |||
4522 | if (LangOpts.OpenMP && LangOpts.OpenMPSimd) | |||
4523 | return; | |||
4524 | for (auto RefExpr : D->varlists()) { | |||
4525 | auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); | |||
4526 | bool PerformInit = | |||
4527 | VD->getAnyInitializer() && | |||
4528 | !VD->getAnyInitializer()->isConstantInitializer(getContext(), | |||
4529 | /*ForRef=*/false); | |||
4530 | ||||
4531 | Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD)); | |||
4532 | if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( | |||
4533 | VD, Addr, RefExpr->getLocStart(), PerformInit)) | |||
4534 | CXXGlobalInits.push_back(InitFunction); | |||
4535 | } | |||
4536 | } | |||
4537 | ||||
4538 | llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { | |||
4539 | llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()]; | |||
4540 | if (InternalId) | |||
4541 | return InternalId; | |||
4542 | ||||
4543 | if (isExternallyVisible(T->getLinkage())) { | |||
4544 | std::string OutName; | |||
4545 | llvm::raw_string_ostream Out(OutName); | |||
4546 | getCXXABI().getMangleContext().mangleTypeName(T, Out); | |||
4547 | ||||
4548 | InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); | |||
4549 | } else { | |||
4550 | InternalId = llvm::MDNode::getDistinct(getLLVMContext(), | |||
4551 | llvm::ArrayRef<llvm::Metadata *>()); | |||
4552 | } | |||
4553 | ||||
4554 | return InternalId; | |||
4555 | } | |||
4556 | ||||
4557 | // Generalize pointer types to a void pointer with the qualifiers of the | |||
4558 | // originally pointed-to type, e.g. 'const char *' and 'char * const *' | |||
4559 | // generalize to 'const void *' while 'char *' and 'const char **' generalize to | |||
4560 | // 'void *'. | |||
4561 | static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) { | |||
4562 | if (!Ty->isPointerType()) | |||
4563 | return Ty; | |||
4564 | ||||
4565 | return Ctx.getPointerType( | |||
4566 | QualType(Ctx.VoidTy).withCVRQualifiers( | |||
4567 | Ty->getPointeeType().getCVRQualifiers())); | |||
4568 | } | |||
4569 | ||||
4570 | // Apply type generalization to a FunctionType's return and argument types | |||
4571 | static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) { | |||
4572 | if (auto *FnType = Ty->getAs<FunctionProtoType>()) { | |||
4573 | SmallVector<QualType, 8> GeneralizedParams; | |||
4574 | for (auto &Param : FnType->param_types()) | |||
4575 | GeneralizedParams.push_back(GeneralizeType(Ctx, Param)); | |||
4576 | ||||
4577 | return Ctx.getFunctionType( | |||
4578 | GeneralizeType(Ctx, FnType->getReturnType()), | |||
4579 | GeneralizedParams, FnType->getExtProtoInfo()); | |||
4580 | } | |||
4581 | ||||
4582 | if (auto *FnType = Ty->getAs<FunctionNoProtoType>()) | |||
4583 | return Ctx.getFunctionNoProtoType( | |||
4584 | GeneralizeType(Ctx, FnType->getReturnType())); | |||
4585 | ||||
4586 | llvm_unreachable("Encountered unknown FunctionType")::llvm::llvm_unreachable_internal("Encountered unknown FunctionType" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/lib/CodeGen/CodeGenModule.cpp" , 4586); | |||
4587 | } | |||
4588 | ||||
4589 | llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) { | |||
4590 | T = GeneralizeFunctionType(getContext(), T); | |||
4591 | ||||
4592 | llvm::Metadata *&InternalId = GeneralizedMetadataIdMap[T.getCanonicalType()]; | |||
4593 | if (InternalId) | |||
4594 | return InternalId; | |||
4595 | ||||
4596 | if (isExternallyVisible(T->getLinkage())) { | |||
4597 | std::string OutName; | |||
4598 | llvm::raw_string_ostream Out(OutName); | |||
4599 | getCXXABI().getMangleContext().mangleTypeName(T, Out); | |||
4600 | Out << ".generalized"; | |||
4601 | ||||
4602 | InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); | |||
4603 | } else { | |||
4604 | InternalId = llvm::MDNode::getDistinct(getLLVMContext(), | |||
4605 | llvm::ArrayRef<llvm::Metadata *>()); | |||
4606 | } | |||
4607 | ||||
4608 | return InternalId; | |||
4609 | } | |||
4610 | ||||
4611 | /// Returns whether this module needs the "all-vtables" type identifier. | |||
4612 | bool CodeGenModule::NeedAllVtablesTypeId() const { | |||
4613 | // Returns true if at least one of vtable-based CFI checkers is enabled and | |||
4614 | // is not in the trapping mode. | |||
4615 | return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) && | |||
4616 | !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) || | |||
4617 | (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) && | |||
4618 | !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) || | |||
4619 | (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) && | |||
4620 | !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) || | |||
4621 | (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) && | |||
4622 | !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast))); | |||
4623 | } | |||
4624 | ||||
4625 | void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable, | |||
4626 | CharUnits Offset, | |||
4627 | const CXXRecordDecl *RD) { | |||
4628 | llvm::Metadata *MD = | |||
4629 | CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); | |||
4630 | VTable->addTypeMetadata(Offset.getQuantity(), MD); | |||
4631 | ||||
4632 | if (CodeGenOpts.SanitizeCfiCrossDso) | |||
4633 | if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) | |||
4634 | VTable->addTypeMetadata(Offset.getQuantity(), | |||
4635 | llvm::ConstantAsMetadata::get(CrossDsoTypeId)); | |||
4636 | ||||
4637 | if (NeedAllVtablesTypeId()) { | |||
4638 | llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables"); | |||
4639 | VTable->addTypeMetadata(Offset.getQuantity(), MD); | |||
4640 | } | |||
4641 | } | |||
4642 | ||||
4643 | // Fills in the supplied string map with the set of target features for the | |||
4644 | // passed in function. | |||
4645 | void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, | |||
4646 | const FunctionDecl *FD) { | |||
4647 | StringRef TargetCPU = Target.getTargetOpts().CPU; | |||
4648 | if (const auto *TD = FD->getAttr<TargetAttr>()) { | |||
4649 | // If we have a TargetAttr build up the feature map based on that. | |||
4650 | TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse(); | |||
4651 | ||||
4652 | ParsedAttr.Features.erase( | |||
4653 | llvm::remove_if(ParsedAttr.Features, | |||
4654 | [&](const std::string &Feat) { | |||
4655 | return !Target.isValidFeatureName( | |||
4656 | StringRef{Feat}.substr(1)); | |||
4657 | }), | |||
4658 | ParsedAttr.Features.end()); | |||
4659 | ||||
4660 | // Make a copy of the features as passed on the command line into the | |||
4661 | // beginning of the additional features from the function to override. | |||
4662 | ParsedAttr.Features.insert(ParsedAttr.Features.begin(), | |||
4663 | Target.getTargetOpts().FeaturesAsWritten.begin(), | |||
4664 | Target.getTargetOpts().FeaturesAsWritten.end()); | |||
4665 | ||||
4666 | if (ParsedAttr.Architecture != "" && | |||
4667 | Target.isValidCPUName(ParsedAttr.Architecture)) | |||
4668 | TargetCPU = ParsedAttr.Architecture; | |||
4669 | ||||
4670 | // Now populate the feature map, first with the TargetCPU which is either | |||
4671 | // the default or a new one from the target attribute string. Then we'll use | |||
4672 | // the passed in features (FeaturesAsWritten) along with the new ones from | |||
4673 | // the attribute. | |||
4674 | Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, | |||
4675 | ParsedAttr.Features); | |||
4676 | } else { | |||
4677 | Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, | |||
4678 | Target.getTargetOpts().Features); | |||
4679 | } | |||
4680 | } | |||
4681 | ||||
4682 | llvm::SanitizerStatReport &CodeGenModule::getSanStats() { | |||
4683 | if (!SanStats) | |||
4684 | SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule()); | |||
4685 | ||||
4686 | return *SanStats; | |||
4687 | } | |||
4688 | llvm::Value * | |||
4689 | CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E, | |||
4690 | CodeGenFunction &CGF) { | |||
4691 | llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType()); | |||
4692 | auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr()); | |||
4693 | auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false); | |||
4694 | return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy, | |||
4695 | "__translate_sampler_initializer"), | |||
4696 | {C}); | |||
4697 | } |
1 | //===- llvm/Support/Casting.h - Allow flexible, checked, casts --*- 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 defines the isa<X>(), cast<X>(), dyn_cast<X>(), cast_or_null<X>(), |
11 | // and dyn_cast_or_null<X>() templates. |
12 | // |
13 | //===----------------------------------------------------------------------===// |
14 | |
15 | #ifndef LLVM_SUPPORT_CASTING_H |
16 | #define LLVM_SUPPORT_CASTING_H |
17 | |
18 | #include "llvm/Support/Compiler.h" |
19 | #include "llvm/Support/type_traits.h" |
20 | #include <cassert> |
21 | #include <memory> |
22 | #include <type_traits> |
23 | |
24 | namespace llvm { |
25 | |
26 | //===----------------------------------------------------------------------===// |
27 | // isa<x> Support Templates |
28 | //===----------------------------------------------------------------------===// |
29 | |
30 | // Define a template that can be specialized by smart pointers to reflect the |
31 | // fact that they are automatically dereferenced, and are not involved with the |
32 | // template selection process... the default implementation is a noop. |
33 | // |
34 | template<typename From> struct simplify_type { |
35 | using SimpleType = From; // The real type this represents... |
36 | |
37 | // An accessor to get the real value... |
38 | static SimpleType &getSimplifiedValue(From &Val) { return Val; } |
39 | }; |
40 | |
41 | template<typename From> struct simplify_type<const From> { |
42 | using NonConstSimpleType = typename simplify_type<From>::SimpleType; |
43 | using SimpleType = |
44 | typename add_const_past_pointer<NonConstSimpleType>::type; |
45 | using RetType = |
46 | typename add_lvalue_reference_if_not_pointer<SimpleType>::type; |
47 | |
48 | static RetType getSimplifiedValue(const From& Val) { |
49 | return simplify_type<From>::getSimplifiedValue(const_cast<From&>(Val)); |
50 | } |
51 | }; |
52 | |
53 | // The core of the implementation of isa<X> is here; To and From should be |
54 | // the names of classes. This template can be specialized to customize the |
55 | // implementation of isa<> without rewriting it from scratch. |
56 | template <typename To, typename From, typename Enabler = void> |
57 | struct isa_impl { |
58 | static inline bool doit(const From &Val) { |
59 | return To::classof(&Val); |
60 | } |
61 | }; |
62 | |
63 | /// \brief Always allow upcasts, and perform no dynamic check for them. |
64 | template <typename To, typename From> |
65 | struct isa_impl< |
66 | To, From, typename std::enable_if<std::is_base_of<To, From>::value>::type> { |
67 | static inline bool doit(const From &) { return true; } |
68 | }; |
69 | |
70 | template <typename To, typename From> struct isa_impl_cl { |
71 | static inline bool doit(const From &Val) { |
72 | return isa_impl<To, From>::doit(Val); |
73 | } |
74 | }; |
75 | |
76 | template <typename To, typename From> struct isa_impl_cl<To, const From> { |
77 | static inline bool doit(const From &Val) { |
78 | return isa_impl<To, From>::doit(Val); |
79 | } |
80 | }; |
81 | |
82 | template <typename To, typename From> |
83 | struct isa_impl_cl<To, const std::unique_ptr<From>> { |
84 | static inline bool doit(const std::unique_ptr<From> &Val) { |
85 | assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer" ) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/Support/Casting.h" , 85, __extension__ __PRETTY_FUNCTION__)); |
86 | return isa_impl_cl<To, From>::doit(*Val); |
87 | } |
88 | }; |
89 | |
90 | template <typename To, typename From> struct isa_impl_cl<To, From*> { |
91 | static inline bool doit(const From *Val) { |
92 | assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer" ) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/Support/Casting.h" , 92, __extension__ __PRETTY_FUNCTION__)); |
93 | return isa_impl<To, From>::doit(*Val); |
94 | } |
95 | }; |
96 | |
97 | template <typename To, typename From> struct isa_impl_cl<To, From*const> { |
98 | static inline bool doit(const From *Val) { |
99 | assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer" ) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/Support/Casting.h" , 99, __extension__ __PRETTY_FUNCTION__)); |
100 | return isa_impl<To, From>::doit(*Val); |
101 | } |
102 | }; |
103 | |
104 | template <typename To, typename From> struct isa_impl_cl<To, const From*> { |
105 | static inline bool doit(const From *Val) { |
106 | assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer" ) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/Support/Casting.h" , 106, __extension__ __PRETTY_FUNCTION__)); |
107 | return isa_impl<To, From>::doit(*Val); |
108 | } |
109 | }; |
110 | |
111 | template <typename To, typename From> struct isa_impl_cl<To, const From*const> { |
112 | static inline bool doit(const From *Val) { |
113 | assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer" ) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/Support/Casting.h" , 113, __extension__ __PRETTY_FUNCTION__)); |
114 | return isa_impl<To, From>::doit(*Val); |
115 | } |
116 | }; |
117 | |
118 | template<typename To, typename From, typename SimpleFrom> |
119 | struct isa_impl_wrap { |
120 | // When From != SimplifiedType, we can simplify the type some more by using |
121 | // the simplify_type template. |
122 | static bool doit(const From &Val) { |
123 | return isa_impl_wrap<To, SimpleFrom, |
124 | typename simplify_type<SimpleFrom>::SimpleType>::doit( |
125 | simplify_type<const From>::getSimplifiedValue(Val)); |
126 | } |
127 | }; |
128 | |
129 | template<typename To, typename FromTy> |
130 | struct isa_impl_wrap<To, FromTy, FromTy> { |
131 | // When From == SimpleType, we are as simple as we are going to get. |
132 | static bool doit(const FromTy &Val) { |
133 | return isa_impl_cl<To,FromTy>::doit(Val); |
134 | } |
135 | }; |
136 | |
137 | // isa<X> - Return true if the parameter to the template is an instance of the |
138 | // template type argument. Used like this: |
139 | // |
140 | // if (isa<Type>(myVal)) { ... } |
141 | // |
142 | template <class X, class Y> LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa(const Y &Val) { |
143 | return isa_impl_wrap<X, const Y, |
144 | typename simplify_type<const Y>::SimpleType>::doit(Val); |
145 | } |
146 | |
147 | //===----------------------------------------------------------------------===// |
148 | // cast<x> Support Templates |
149 | //===----------------------------------------------------------------------===// |
150 | |
151 | template<class To, class From> struct cast_retty; |
152 | |
153 | // Calculate what type the 'cast' function should return, based on a requested |
154 | // type of To and a source type of From. |
155 | template<class To, class From> struct cast_retty_impl { |
156 | using ret_type = To &; // Normal case, return Ty& |
157 | }; |
158 | template<class To, class From> struct cast_retty_impl<To, const From> { |
159 | using ret_type = const To &; // Normal case, return Ty& |
160 | }; |
161 | |
162 | template<class To, class From> struct cast_retty_impl<To, From*> { |
163 | using ret_type = To *; // Pointer arg case, return Ty* |
164 | }; |
165 | |
166 | template<class To, class From> struct cast_retty_impl<To, const From*> { |
167 | using ret_type = const To *; // Constant pointer arg case, return const Ty* |
168 | }; |
169 | |
170 | template<class To, class From> struct cast_retty_impl<To, const From*const> { |
171 | using ret_type = const To *; // Constant pointer arg case, return const Ty* |
172 | }; |
173 | |
174 | template <class To, class From> |
175 | struct cast_retty_impl<To, std::unique_ptr<From>> { |
176 | private: |
177 | using PointerType = typename cast_retty_impl<To, From *>::ret_type; |
178 | using ResultType = typename std::remove_pointer<PointerType>::type; |
179 | |
180 | public: |
181 | using ret_type = std::unique_ptr<ResultType>; |
182 | }; |
183 | |
184 | template<class To, class From, class SimpleFrom> |
185 | struct cast_retty_wrap { |
186 | // When the simplified type and the from type are not the same, use the type |
187 | // simplifier to reduce the type, then reuse cast_retty_impl to get the |
188 | // resultant type. |
189 | using ret_type = typename cast_retty<To, SimpleFrom>::ret_type; |
190 | }; |
191 | |
192 | template<class To, class FromTy> |
193 | struct cast_retty_wrap<To, FromTy, FromTy> { |
194 | // When the simplified type is equal to the from type, use it directly. |
195 | using ret_type = typename cast_retty_impl<To,FromTy>::ret_type; |
196 | }; |
197 | |
198 | template<class To, class From> |
199 | struct cast_retty { |
200 | using ret_type = typename cast_retty_wrap< |
201 | To, From, typename simplify_type<From>::SimpleType>::ret_type; |
202 | }; |
203 | |
204 | // Ensure the non-simple values are converted using the simplify_type template |
205 | // that may be specialized by smart pointers... |
206 | // |
207 | template<class To, class From, class SimpleFrom> struct cast_convert_val { |
208 | // This is not a simple type, use the template to simplify it... |
209 | static typename cast_retty<To, From>::ret_type doit(From &Val) { |
210 | return cast_convert_val<To, SimpleFrom, |
211 | typename simplify_type<SimpleFrom>::SimpleType>::doit( |
212 | simplify_type<From>::getSimplifiedValue(Val)); |
213 | } |
214 | }; |
215 | |
216 | template<class To, class FromTy> struct cast_convert_val<To,FromTy,FromTy> { |
217 | // This _is_ a simple type, just cast it. |
218 | static typename cast_retty<To, FromTy>::ret_type doit(const FromTy &Val) { |
219 | typename cast_retty<To, FromTy>::ret_type Res2 |
220 | = (typename cast_retty<To, FromTy>::ret_type)const_cast<FromTy&>(Val); |
221 | return Res2; |
222 | } |
223 | }; |
224 | |
225 | template <class X> struct is_simple_type { |
226 | static const bool value = |
227 | std::is_same<X, typename simplify_type<X>::SimpleType>::value; |
228 | }; |
229 | |
230 | // cast<X> - Return the argument parameter cast to the specified type. This |
231 | // casting operator asserts that the type is correct, so it does not return null |
232 | // on failure. It does not allow a null argument (use cast_or_null for that). |
233 | // It is typically used like this: |
234 | // |
235 | // cast<Instruction>(myVal)->getParent() |
236 | // |
237 | template <class X, class Y> |
238 | inline typename std::enable_if<!is_simple_type<Y>::value, |
239 | typename cast_retty<X, const Y>::ret_type>::type |
240 | cast(const Y &Val) { |
241 | assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!" ) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/Support/Casting.h" , 241, __extension__ __PRETTY_FUNCTION__)); |
242 | return cast_convert_val< |
243 | X, const Y, typename simplify_type<const Y>::SimpleType>::doit(Val); |
244 | } |
245 | |
246 | template <class X, class Y> |
247 | inline typename cast_retty<X, Y>::ret_type cast(Y &Val) { |
248 | assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!" ) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/Support/Casting.h" , 248, __extension__ __PRETTY_FUNCTION__)); |
249 | return cast_convert_val<X, Y, |
250 | typename simplify_type<Y>::SimpleType>::doit(Val); |
251 | } |
252 | |
253 | template <class X, class Y> |
254 | inline typename cast_retty<X, Y *>::ret_type cast(Y *Val) { |
255 | assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!" ) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/Support/Casting.h" , 255, __extension__ __PRETTY_FUNCTION__)); |
256 | return cast_convert_val<X, Y*, |
257 | typename simplify_type<Y*>::SimpleType>::doit(Val); |
258 | } |
259 | |
260 | template <class X, class Y> |
261 | inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type |
262 | cast(std::unique_ptr<Y> &&Val) { |
263 | assert(isa<X>(Val.get()) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val.get()) && "cast<Ty>() argument of incompatible type!") ? void (0 ) : __assert_fail ("isa<X>(Val.get()) && \"cast<Ty>() argument of incompatible type!\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/Support/Casting.h" , 263, __extension__ __PRETTY_FUNCTION__)); |
264 | using ret_type = typename cast_retty<X, std::unique_ptr<Y>>::ret_type; |
265 | return ret_type( |
266 | cast_convert_val<X, Y *, typename simplify_type<Y *>::SimpleType>::doit( |
267 | Val.release())); |
268 | } |
269 | |
270 | // cast_or_null<X> - Functionally identical to cast, except that a null value is |
271 | // accepted. |
272 | // |
273 | template <class X, class Y> |
274 | LLVM_NODISCARD[[clang::warn_unused_result]] inline |
275 | typename std::enable_if<!is_simple_type<Y>::value, |
276 | typename cast_retty<X, const Y>::ret_type>::type |
277 | cast_or_null(const Y &Val) { |
278 | if (!Val) |
279 | return nullptr; |
280 | assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!" ) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/Support/Casting.h" , 280, __extension__ __PRETTY_FUNCTION__)); |
281 | return cast<X>(Val); |
282 | } |
283 | |
284 | template <class X, class Y> |
285 | LLVM_NODISCARD[[clang::warn_unused_result]] inline |
286 | typename std::enable_if<!is_simple_type<Y>::value, |
287 | typename cast_retty<X, Y>::ret_type>::type |
288 | cast_or_null(Y &Val) { |
289 | if (!Val) |
290 | return nullptr; |
291 | assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!" ) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/Support/Casting.h" , 291, __extension__ __PRETTY_FUNCTION__)); |
292 | return cast<X>(Val); |
293 | } |
294 | |
295 | template <class X, class Y> |
296 | LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type |
297 | cast_or_null(Y *Val) { |
298 | if (!Val) return nullptr; |
299 | assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!" ) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/include/llvm/Support/Casting.h" , 299, __extension__ __PRETTY_FUNCTION__)); |
300 | return cast<X>(Val); |
301 | } |
302 | |
303 | template <class X, class Y> |
304 | inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type |
305 | cast_or_null(std::unique_ptr<Y> &&Val) { |
306 | if (!Val) |
307 | return nullptr; |
308 | return cast<X>(std::move(Val)); |
309 | } |
310 | |
311 | // dyn_cast<X> - Return the argument parameter cast to the specified type. This |
312 | // casting operator returns null if the argument is of the wrong type, so it can |
313 | // be used to test for a type as well as cast if successful. This should be |
314 | // used in the context of an if statement like this: |
315 | // |
316 | // if (const Instruction *I = dyn_cast<Instruction>(myVal)) { ... } |
317 | // |
318 | |
319 | template <class X, class Y> |
320 | LLVM_NODISCARD[[clang::warn_unused_result]] inline |
321 | typename std::enable_if<!is_simple_type<Y>::value, |
322 | typename cast_retty<X, const Y>::ret_type>::type |
323 | dyn_cast(const Y &Val) { |
324 | return isa<X>(Val) ? cast<X>(Val) : nullptr; |
325 | } |
326 | |
327 | template <class X, class Y> |
328 | LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y>::ret_type dyn_cast(Y &Val) { |
329 | return isa<X>(Val) ? cast<X>(Val) : nullptr; |
330 | } |
331 | |
332 | template <class X, class Y> |
333 | LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type dyn_cast(Y *Val) { |
334 | return isa<X>(Val) ? cast<X>(Val) : nullptr; |
335 | } |
336 | |
337 | // dyn_cast_or_null<X> - Functionally identical to dyn_cast, except that a null |
338 | // value is accepted. |
339 | // |
340 | template <class X, class Y> |
341 | LLVM_NODISCARD[[clang::warn_unused_result]] inline |
342 | typename std::enable_if<!is_simple_type<Y>::value, |
343 | typename cast_retty<X, const Y>::ret_type>::type |
344 | dyn_cast_or_null(const Y &Val) { |
345 | return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr; |
346 | } |
347 | |
348 | template <class X, class Y> |
349 | LLVM_NODISCARD[[clang::warn_unused_result]] inline |
350 | typename std::enable_if<!is_simple_type<Y>::value, |
351 | typename cast_retty<X, Y>::ret_type>::type |
352 | dyn_cast_or_null(Y &Val) { |
353 | return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr; |
354 | } |
355 | |
356 | template <class X, class Y> |
357 | LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type |
358 | dyn_cast_or_null(Y *Val) { |
359 | return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr; |
360 | } |
361 | |
362 | // unique_dyn_cast<X> - Given a unique_ptr<Y>, try to return a unique_ptr<X>, |
363 | // taking ownership of the input pointer iff isa<X>(Val) is true. If the |
364 | // cast is successful, From refers to nullptr on exit and the casted value |
365 | // is returned. If the cast is unsuccessful, the function returns nullptr |
366 | // and From is unchanged. |
367 | template <class X, class Y> |
368 | LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &Val) |
369 | -> decltype(cast<X>(Val)) { |
370 | if (!isa<X>(Val)) |
371 | return nullptr; |
372 | return cast<X>(std::move(Val)); |
373 | } |
374 | |
375 | template <class X, class Y> |
376 | LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &&Val) |
377 | -> decltype(cast<X>(Val)) { |
378 | return unique_dyn_cast<X, Y>(Val); |
379 | } |
380 | |
381 | // dyn_cast_or_null<X> - Functionally identical to unique_dyn_cast, except that |
382 | // a null value is accepted. |
383 | template <class X, class Y> |
384 | LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &Val) |
385 | -> decltype(cast<X>(Val)) { |
386 | if (!Val) |
387 | return nullptr; |
388 | return unique_dyn_cast<X, Y>(Val); |
389 | } |
390 | |
391 | template <class X, class Y> |
392 | LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &&Val) |
393 | -> decltype(cast<X>(Val)) { |
394 | return unique_dyn_cast_or_null<X, Y>(Val); |
395 | } |
396 | |
397 | } // end namespace llvm |
398 | |
399 | #endif // LLVM_SUPPORT_CASTING_H |
1 | //===- Decl.h - Classes for representing declarations -----------*- 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 defines the Decl subclasses. |
11 | // |
12 | //===----------------------------------------------------------------------===// |
13 | |
14 | #ifndef LLVM_CLANG_AST_DECL_H |
15 | #define LLVM_CLANG_AST_DECL_H |
16 | |
17 | #include "clang/AST/APValue.h" |
18 | #include "clang/AST/DeclBase.h" |
19 | #include "clang/AST/DeclarationName.h" |
20 | #include "clang/AST/ExternalASTSource.h" |
21 | #include "clang/AST/NestedNameSpecifier.h" |
22 | #include "clang/AST/Redeclarable.h" |
23 | #include "clang/AST/Type.h" |
24 | #include "clang/Basic/AddressSpaces.h" |
25 | #include "clang/Basic/Diagnostic.h" |
26 | #include "clang/Basic/IdentifierTable.h" |
27 | #include "clang/Basic/LLVM.h" |
28 | #include "clang/Basic/Linkage.h" |
29 | #include "clang/Basic/OperatorKinds.h" |
30 | #include "clang/Basic/PartialDiagnostic.h" |
31 | #include "clang/Basic/PragmaKinds.h" |
32 | #include "clang/Basic/SourceLocation.h" |
33 | #include "clang/Basic/Specifiers.h" |
34 | #include "clang/Basic/Visibility.h" |
35 | #include "llvm/ADT/APSInt.h" |
36 | #include "llvm/ADT/ArrayRef.h" |
37 | #include "llvm/ADT/Optional.h" |
38 | #include "llvm/ADT/PointerIntPair.h" |
39 | #include "llvm/ADT/PointerUnion.h" |
40 | #include "llvm/ADT/StringRef.h" |
41 | #include "llvm/ADT/iterator_range.h" |
42 | #include "llvm/Support/Casting.h" |
43 | #include "llvm/Support/Compiler.h" |
44 | #include "llvm/Support/TrailingObjects.h" |
45 | #include <cassert> |
46 | #include <cstddef> |
47 | #include <cstdint> |
48 | #include <string> |
49 | #include <utility> |
50 | |
51 | namespace clang { |
52 | |
53 | class ASTContext; |
54 | struct ASTTemplateArgumentListInfo; |
55 | class Attr; |
56 | class CompoundStmt; |
57 | class DependentFunctionTemplateSpecializationInfo; |
58 | class EnumDecl; |
59 | class Expr; |
60 | class FunctionTemplateDecl; |
61 | class FunctionTemplateSpecializationInfo; |
62 | class LabelStmt; |
63 | class MemberSpecializationInfo; |
64 | class Module; |
65 | class NamespaceDecl; |
66 | class ParmVarDecl; |
67 | class RecordDecl; |
68 | class Stmt; |
69 | class StringLiteral; |
70 | class TagDecl; |
71 | class TemplateArgumentList; |
72 | class TemplateArgumentListInfo; |
73 | class TemplateParameterList; |
74 | class TypeAliasTemplateDecl; |
75 | class TypeLoc; |
76 | class UnresolvedSetImpl; |
77 | class VarTemplateDecl; |
78 | |
79 | /// \brief A container of type source information. |
80 | /// |
81 | /// A client can read the relevant info using TypeLoc wrappers, e.g: |
82 | /// @code |
83 | /// TypeLoc TL = TypeSourceInfo->getTypeLoc(); |
84 | /// TL.getStartLoc().print(OS, SrcMgr); |
85 | /// @endcode |
86 | class TypeSourceInfo { |
87 | // Contains a memory block after the class, used for type source information, |
88 | // allocated by ASTContext. |
89 | friend class ASTContext; |
90 | |
91 | QualType Ty; |
92 | |
93 | TypeSourceInfo(QualType ty) : Ty(ty) {} |
94 | |
95 | public: |
96 | /// \brief Return the type wrapped by this type source info. |
97 | QualType getType() const { return Ty; } |
98 | |
99 | /// \brief Return the TypeLoc wrapper for the type source info. |
100 | TypeLoc getTypeLoc() const; // implemented in TypeLoc.h |
101 | |
102 | /// \brief Override the type stored in this TypeSourceInfo. Use with caution! |
103 | void overrideType(QualType T) { Ty = T; } |
104 | }; |
105 | |
106 | /// TranslationUnitDecl - The top declaration context. |
107 | class TranslationUnitDecl : public Decl, public DeclContext { |
108 | ASTContext &Ctx; |
109 | |
110 | /// The (most recently entered) anonymous namespace for this |
111 | /// translation unit, if one has been created. |
112 | NamespaceDecl *AnonymousNamespace = nullptr; |
113 | |
114 | explicit TranslationUnitDecl(ASTContext &ctx); |
115 | |
116 | virtual void anchor(); |
117 | |
118 | public: |
119 | ASTContext &getASTContext() const { return Ctx; } |
120 | |
121 | NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; } |
122 | void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; } |
123 | |
124 | static TranslationUnitDecl *Create(ASTContext &C); |
125 | |
126 | // Implement isa/cast/dyncast/etc. |
127 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
128 | static bool classofKind(Kind K) { return K == TranslationUnit; } |
129 | static DeclContext *castToDeclContext(const TranslationUnitDecl *D) { |
130 | return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D)); |
131 | } |
132 | static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) { |
133 | return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC)); |
134 | } |
135 | }; |
136 | |
137 | /// \brief Represents a `#pragma comment` line. Always a child of |
138 | /// TranslationUnitDecl. |
139 | class PragmaCommentDecl final |
140 | : public Decl, |
141 | private llvm::TrailingObjects<PragmaCommentDecl, char> { |
142 | friend class ASTDeclReader; |
143 | friend class ASTDeclWriter; |
144 | friend TrailingObjects; |
145 | |
146 | PragmaMSCommentKind CommentKind; |
147 | |
148 | PragmaCommentDecl(TranslationUnitDecl *TU, SourceLocation CommentLoc, |
149 | PragmaMSCommentKind CommentKind) |
150 | : Decl(PragmaComment, TU, CommentLoc), CommentKind(CommentKind) {} |
151 | |
152 | virtual void anchor(); |
153 | |
154 | public: |
155 | static PragmaCommentDecl *Create(const ASTContext &C, TranslationUnitDecl *DC, |
156 | SourceLocation CommentLoc, |
157 | PragmaMSCommentKind CommentKind, |
158 | StringRef Arg); |
159 | static PragmaCommentDecl *CreateDeserialized(ASTContext &C, unsigned ID, |
160 | unsigned ArgSize); |
161 | |
162 | PragmaMSCommentKind getCommentKind() const { return CommentKind; } |
163 | |
164 | StringRef getArg() const { return getTrailingObjects<char>(); } |
165 | |
166 | // Implement isa/cast/dyncast/etc. |
167 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
168 | static bool classofKind(Kind K) { return K == PragmaComment; } |
169 | }; |
170 | |
171 | /// \brief Represents a `#pragma detect_mismatch` line. Always a child of |
172 | /// TranslationUnitDecl. |
173 | class PragmaDetectMismatchDecl final |
174 | : public Decl, |
175 | private llvm::TrailingObjects<PragmaDetectMismatchDecl, char> { |
176 | friend class ASTDeclReader; |
177 | friend class ASTDeclWriter; |
178 | friend TrailingObjects; |
179 | |
180 | size_t ValueStart; |
181 | |
182 | PragmaDetectMismatchDecl(TranslationUnitDecl *TU, SourceLocation Loc, |
183 | size_t ValueStart) |
184 | : Decl(PragmaDetectMismatch, TU, Loc), ValueStart(ValueStart) {} |
185 | |
186 | virtual void anchor(); |
187 | |
188 | public: |
189 | static PragmaDetectMismatchDecl *Create(const ASTContext &C, |
190 | TranslationUnitDecl *DC, |
191 | SourceLocation Loc, StringRef Name, |
192 | StringRef Value); |
193 | static PragmaDetectMismatchDecl * |
194 | CreateDeserialized(ASTContext &C, unsigned ID, unsigned NameValueSize); |
195 | |
196 | StringRef getName() const { return getTrailingObjects<char>(); } |
197 | StringRef getValue() const { return getTrailingObjects<char>() + ValueStart; } |
198 | |
199 | // Implement isa/cast/dyncast/etc. |
200 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
201 | static bool classofKind(Kind K) { return K == PragmaDetectMismatch; } |
202 | }; |
203 | |
204 | /// \brief Declaration context for names declared as extern "C" in C++. This |
205 | /// is neither the semantic nor lexical context for such declarations, but is |
206 | /// used to check for conflicts with other extern "C" declarations. Example: |
207 | /// |
208 | /// \code |
209 | /// namespace N { extern "C" void f(); } // #1 |
210 | /// void N::f() {} // #2 |
211 | /// namespace M { extern "C" void f(); } // #3 |
212 | /// \endcode |
213 | /// |
214 | /// The semantic context of #1 is namespace N and its lexical context is the |
215 | /// LinkageSpecDecl; the semantic context of #2 is namespace N and its lexical |
216 | /// context is the TU. However, both declarations are also visible in the |
217 | /// extern "C" context. |
218 | /// |
219 | /// The declaration at #3 finds it is a redeclaration of \c N::f through |
220 | /// lookup in the extern "C" context. |
221 | class ExternCContextDecl : public Decl, public DeclContext { |
222 | explicit ExternCContextDecl(TranslationUnitDecl *TU) |
223 | : Decl(ExternCContext, TU, SourceLocation()), |
224 | DeclContext(ExternCContext) {} |
225 | |
226 | virtual void anchor(); |
227 | |
228 | public: |
229 | static ExternCContextDecl *Create(const ASTContext &C, |
230 | TranslationUnitDecl *TU); |
231 | |
232 | // Implement isa/cast/dyncast/etc. |
233 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
234 | static bool classofKind(Kind K) { return K == ExternCContext; } |
235 | static DeclContext *castToDeclContext(const ExternCContextDecl *D) { |
236 | return static_cast<DeclContext *>(const_cast<ExternCContextDecl*>(D)); |
237 | } |
238 | static ExternCContextDecl *castFromDeclContext(const DeclContext *DC) { |
239 | return static_cast<ExternCContextDecl *>(const_cast<DeclContext*>(DC)); |
240 | } |
241 | }; |
242 | |
243 | /// NamedDecl - This represents a decl with a name. Many decls have names such |
244 | /// as ObjCMethodDecl, but not \@class, etc. |
245 | class NamedDecl : public Decl { |
246 | /// Name - The name of this declaration, which is typically a normal |
247 | /// identifier but may also be a special kind of name (C++ |
248 | /// constructor, Objective-C selector, etc.) |
249 | DeclarationName Name; |
250 | |
251 | virtual void anchor(); |
252 | |
253 | private: |
254 | NamedDecl *getUnderlyingDeclImpl() LLVM_READONLY__attribute__((__pure__)); |
255 | |
256 | protected: |
257 | NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N) |
258 | : Decl(DK, DC, L), Name(N) {} |
259 | |
260 | public: |
261 | /// getIdentifier - Get the identifier that names this declaration, |
262 | /// if there is one. This will return NULL if this declaration has |
263 | /// no name (e.g., for an unnamed class) or if the name is a special |
264 | /// name (C++ constructor, Objective-C selector, etc.). |
265 | IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); } |
266 | |
267 | /// getName - Get the name of identifier for this declaration as a StringRef. |
268 | /// This requires that the declaration have a name and that it be a simple |
269 | /// identifier. |
270 | StringRef getName() const { |
271 | assert(Name.isIdentifier() && "Name is not a simple identifier")(static_cast <bool> (Name.isIdentifier() && "Name is not a simple identifier" ) ? void (0) : __assert_fail ("Name.isIdentifier() && \"Name is not a simple identifier\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 271, __extension__ __PRETTY_FUNCTION__)); |
272 | return getIdentifier() ? getIdentifier()->getName() : ""; |
273 | } |
274 | |
275 | /// getNameAsString - Get a human-readable name for the declaration, even if |
276 | /// it is one of the special kinds of names (C++ constructor, Objective-C |
277 | /// selector, etc). Creating this name requires expensive string |
278 | /// manipulation, so it should be called only when performance doesn't matter. |
279 | /// For simple declarations, getNameAsCString() should suffice. |
280 | // |
281 | // FIXME: This function should be renamed to indicate that it is not just an |
282 | // alternate form of getName(), and clients should move as appropriate. |
283 | // |
284 | // FIXME: Deprecated, move clients to getName(). |
285 | std::string getNameAsString() const { return Name.getAsString(); } |
286 | |
287 | virtual void printName(raw_ostream &os) const; |
288 | |
289 | /// getDeclName - Get the actual, stored name of the declaration, |
290 | /// which may be a special name. |
291 | DeclarationName getDeclName() const { return Name; } |
292 | |
293 | /// \brief Set the name of this declaration. |
294 | void setDeclName(DeclarationName N) { Name = N; } |
295 | |
296 | /// printQualifiedName - Returns human-readable qualified name for |
297 | /// declaration, like A::B::i, for i being member of namespace A::B. |
298 | /// If declaration is not member of context which can be named (record, |
299 | /// namespace), it will return same result as printName(). |
300 | /// Creating this name is expensive, so it should be called only when |
301 | /// performance doesn't matter. |
302 | void printQualifiedName(raw_ostream &OS) const; |
303 | void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const; |
304 | |
305 | // FIXME: Remove string version. |
306 | std::string getQualifiedNameAsString() const; |
307 | |
308 | /// Appends a human-readable name for this declaration into the given stream. |
309 | /// |
310 | /// This is the method invoked by Sema when displaying a NamedDecl |
311 | /// in a diagnostic. It does not necessarily produce the same |
312 | /// result as printName(); for example, class template |
313 | /// specializations are printed with their template arguments. |
314 | virtual void getNameForDiagnostic(raw_ostream &OS, |
315 | const PrintingPolicy &Policy, |
316 | bool Qualified) const; |
317 | |
318 | /// \brief Determine whether this declaration, if |
319 | /// known to be well-formed within its context, will replace the |
320 | /// declaration OldD if introduced into scope. A declaration will |
321 | /// replace another declaration if, for example, it is a |
322 | /// redeclaration of the same variable or function, but not if it is |
323 | /// a declaration of a different kind (function vs. class) or an |
324 | /// overloaded function. |
325 | /// |
326 | /// \param IsKnownNewer \c true if this declaration is known to be newer |
327 | /// than \p OldD (for instance, if this declaration is newly-created). |
328 | bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer = true) const; |
329 | |
330 | /// \brief Determine whether this declaration has linkage. |
331 | bool hasLinkage() const; |
332 | |
333 | using Decl::isModulePrivate; |
334 | using Decl::setModulePrivate; |
335 | |
336 | /// \brief Determine whether this declaration is a C++ class member. |
337 | bool isCXXClassMember() const { |
338 | const DeclContext *DC = getDeclContext(); |
339 | |
340 | // C++0x [class.mem]p1: |
341 | // The enumerators of an unscoped enumeration defined in |
342 | // the class are members of the class. |
343 | if (isa<EnumDecl>(DC)) |
344 | DC = DC->getRedeclContext(); |
345 | |
346 | return DC->isRecord(); |
347 | } |
348 | |
349 | /// \brief Determine whether the given declaration is an instance member of |
350 | /// a C++ class. |
351 | bool isCXXInstanceMember() const; |
352 | |
353 | /// \brief Determine what kind of linkage this entity has. |
354 | /// This is not the linkage as defined by the standard or the codegen notion |
355 | /// of linkage. It is just an implementation detail that is used to compute |
356 | /// those. |
357 | Linkage getLinkageInternal() const; |
358 | |
359 | /// \brief Get the linkage from a semantic point of view. Entities in |
360 | /// anonymous namespaces are external (in c++98). |
361 | Linkage getFormalLinkage() const { |
362 | return clang::getFormalLinkage(getLinkageInternal()); |
363 | } |
364 | |
365 | /// \brief True if this decl has external linkage. |
366 | bool hasExternalFormalLinkage() const { |
367 | return isExternalFormalLinkage(getLinkageInternal()); |
368 | } |
369 | |
370 | bool isExternallyVisible() const { |
371 | return clang::isExternallyVisible(getLinkageInternal()); |
372 | } |
373 | |
374 | /// Determine whether this declaration can be redeclared in a |
375 | /// different translation unit. |
376 | bool isExternallyDeclarable() const { |
377 | return isExternallyVisible() && !getOwningModuleForLinkage(); |
378 | } |
379 | |
380 | /// \brief Determines the visibility of this entity. |
381 | Visibility getVisibility() const { |
382 | return getLinkageAndVisibility().getVisibility(); |
383 | } |
384 | |
385 | /// \brief Determines the linkage and visibility of this entity. |
386 | LinkageInfo getLinkageAndVisibility() const; |
387 | |
388 | /// Kinds of explicit visibility. |
389 | enum ExplicitVisibilityKind { |
390 | /// Do an LV computation for, ultimately, a type. |
391 | /// Visibility may be restricted by type visibility settings and |
392 | /// the visibility of template arguments. |
393 | VisibilityForType, |
394 | |
395 | /// Do an LV computation for, ultimately, a non-type declaration. |
396 | /// Visibility may be restricted by value visibility settings and |
397 | /// the visibility of template arguments. |
398 | VisibilityForValue |
399 | }; |
400 | |
401 | /// \brief If visibility was explicitly specified for this |
402 | /// declaration, return that visibility. |
403 | Optional<Visibility> |
404 | getExplicitVisibility(ExplicitVisibilityKind kind) const; |
405 | |
406 | /// \brief True if the computed linkage is valid. Used for consistency |
407 | /// checking. Should always return true. |
408 | bool isLinkageValid() const; |
409 | |
410 | /// \brief True if something has required us to compute the linkage |
411 | /// of this declaration. |
412 | /// |
413 | /// Language features which can retroactively change linkage (like a |
414 | /// typedef name for linkage purposes) may need to consider this, |
415 | /// but hopefully only in transitory ways during parsing. |
416 | bool hasLinkageBeenComputed() const { |
417 | return hasCachedLinkage(); |
418 | } |
419 | |
420 | /// \brief Looks through UsingDecls and ObjCCompatibleAliasDecls for |
421 | /// the underlying named decl. |
422 | NamedDecl *getUnderlyingDecl() { |
423 | // Fast-path the common case. |
424 | if (this->getKind() != UsingShadow && |
425 | this->getKind() != ConstructorUsingShadow && |
426 | this->getKind() != ObjCCompatibleAlias && |
427 | this->getKind() != NamespaceAlias) |
428 | return this; |
429 | |
430 | return getUnderlyingDeclImpl(); |
431 | } |
432 | const NamedDecl *getUnderlyingDecl() const { |
433 | return const_cast<NamedDecl*>(this)->getUnderlyingDecl(); |
434 | } |
435 | |
436 | NamedDecl *getMostRecentDecl() { |
437 | return cast<NamedDecl>(static_cast<Decl *>(this)->getMostRecentDecl()); |
438 | } |
439 | const NamedDecl *getMostRecentDecl() const { |
440 | return const_cast<NamedDecl*>(this)->getMostRecentDecl(); |
441 | } |
442 | |
443 | ObjCStringFormatFamily getObjCFStringFormattingFamily() const; |
444 | |
445 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
446 | static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; } |
447 | }; |
448 | |
449 | inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) { |
450 | ND.printName(OS); |
451 | return OS; |
452 | } |
453 | |
454 | /// LabelDecl - Represents the declaration of a label. Labels also have a |
455 | /// corresponding LabelStmt, which indicates the position that the label was |
456 | /// defined at. For normal labels, the location of the decl is the same as the |
457 | /// location of the statement. For GNU local labels (__label__), the decl |
458 | /// location is where the __label__ is. |
459 | class LabelDecl : public NamedDecl { |
460 | LabelStmt *TheStmt; |
461 | StringRef MSAsmName; |
462 | bool MSAsmNameResolved = false; |
463 | |
464 | /// LocStart - For normal labels, this is the same as the main declaration |
465 | /// label, i.e., the location of the identifier; for GNU local labels, |
466 | /// this is the location of the __label__ keyword. |
467 | SourceLocation LocStart; |
468 | |
469 | LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II, |
470 | LabelStmt *S, SourceLocation StartL) |
471 | : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {} |
472 | |
473 | void anchor() override; |
474 | |
475 | public: |
476 | static LabelDecl *Create(ASTContext &C, DeclContext *DC, |
477 | SourceLocation IdentL, IdentifierInfo *II); |
478 | static LabelDecl *Create(ASTContext &C, DeclContext *DC, |
479 | SourceLocation IdentL, IdentifierInfo *II, |
480 | SourceLocation GnuLabelL); |
481 | static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
482 | |
483 | LabelStmt *getStmt() const { return TheStmt; } |
484 | void setStmt(LabelStmt *T) { TheStmt = T; } |
485 | |
486 | bool isGnuLocal() const { return LocStart != getLocation(); } |
487 | void setLocStart(SourceLocation L) { LocStart = L; } |
488 | |
489 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
490 | return SourceRange(LocStart, getLocation()); |
491 | } |
492 | |
493 | bool isMSAsmLabel() const { return !MSAsmName.empty(); } |
494 | bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; } |
495 | void setMSAsmLabel(StringRef Name); |
496 | StringRef getMSAsmLabel() const { return MSAsmName; } |
497 | void setMSAsmLabelResolved() { MSAsmNameResolved = true; } |
498 | |
499 | // Implement isa/cast/dyncast/etc. |
500 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
501 | static bool classofKind(Kind K) { return K == Label; } |
502 | }; |
503 | |
504 | /// NamespaceDecl - Represent a C++ namespace. |
505 | class NamespaceDecl : public NamedDecl, public DeclContext, |
506 | public Redeclarable<NamespaceDecl> |
507 | { |
508 | /// LocStart - The starting location of the source range, pointing |
509 | /// to either the namespace or the inline keyword. |
510 | SourceLocation LocStart; |
511 | |
512 | /// RBraceLoc - The ending location of the source range. |
513 | SourceLocation RBraceLoc; |
514 | |
515 | /// \brief A pointer to either the anonymous namespace that lives just inside |
516 | /// this namespace or to the first namespace in the chain (the latter case |
517 | /// only when this is not the first in the chain), along with a |
518 | /// boolean value indicating whether this is an inline namespace. |
519 | llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline; |
520 | |
521 | NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline, |
522 | SourceLocation StartLoc, SourceLocation IdLoc, |
523 | IdentifierInfo *Id, NamespaceDecl *PrevDecl); |
524 | |
525 | using redeclarable_base = Redeclarable<NamespaceDecl>; |
526 | |
527 | NamespaceDecl *getNextRedeclarationImpl() override; |
528 | NamespaceDecl *getPreviousDeclImpl() override; |
529 | NamespaceDecl *getMostRecentDeclImpl() override; |
530 | |
531 | public: |
532 | friend class ASTDeclReader; |
533 | friend class ASTDeclWriter; |
534 | |
535 | static NamespaceDecl *Create(ASTContext &C, DeclContext *DC, |
536 | bool Inline, SourceLocation StartLoc, |
537 | SourceLocation IdLoc, IdentifierInfo *Id, |
538 | NamespaceDecl *PrevDecl); |
539 | |
540 | static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
541 | |
542 | using redecl_range = redeclarable_base::redecl_range; |
543 | using redecl_iterator = redeclarable_base::redecl_iterator; |
544 | |
545 | using redeclarable_base::redecls_begin; |
546 | using redeclarable_base::redecls_end; |
547 | using redeclarable_base::redecls; |
548 | using redeclarable_base::getPreviousDecl; |
549 | using redeclarable_base::getMostRecentDecl; |
550 | using redeclarable_base::isFirstDecl; |
551 | |
552 | /// \brief Returns true if this is an anonymous namespace declaration. |
553 | /// |
554 | /// For example: |
555 | /// \code |
556 | /// namespace { |
557 | /// ... |
558 | /// }; |
559 | /// \endcode |
560 | /// q.v. C++ [namespace.unnamed] |
561 | bool isAnonymousNamespace() const { |
562 | return !getIdentifier(); |
563 | } |
564 | |
565 | /// \brief Returns true if this is an inline namespace declaration. |
566 | bool isInline() const { |
567 | return AnonOrFirstNamespaceAndInline.getInt(); |
568 | } |
569 | |
570 | /// \brief Set whether this is an inline namespace declaration. |
571 | void setInline(bool Inline) { |
572 | AnonOrFirstNamespaceAndInline.setInt(Inline); |
573 | } |
574 | |
575 | /// \brief Get the original (first) namespace declaration. |
576 | NamespaceDecl *getOriginalNamespace(); |
577 | |
578 | /// \brief Get the original (first) namespace declaration. |
579 | const NamespaceDecl *getOriginalNamespace() const; |
580 | |
581 | /// \brief Return true if this declaration is an original (first) declaration |
582 | /// of the namespace. This is false for non-original (subsequent) namespace |
583 | /// declarations and anonymous namespaces. |
584 | bool isOriginalNamespace() const; |
585 | |
586 | /// \brief Retrieve the anonymous namespace nested inside this namespace, |
587 | /// if any. |
588 | NamespaceDecl *getAnonymousNamespace() const { |
589 | return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer(); |
590 | } |
591 | |
592 | void setAnonymousNamespace(NamespaceDecl *D) { |
593 | getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D); |
594 | } |
595 | |
596 | /// Retrieves the canonical declaration of this namespace. |
597 | NamespaceDecl *getCanonicalDecl() override { |
598 | return getOriginalNamespace(); |
599 | } |
600 | const NamespaceDecl *getCanonicalDecl() const { |
601 | return getOriginalNamespace(); |
602 | } |
603 | |
604 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
605 | return SourceRange(LocStart, RBraceLoc); |
606 | } |
607 | |
608 | SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; } |
609 | SourceLocation getRBraceLoc() const { return RBraceLoc; } |
610 | void setLocStart(SourceLocation L) { LocStart = L; } |
611 | void setRBraceLoc(SourceLocation L) { RBraceLoc = L; } |
612 | |
613 | // Implement isa/cast/dyncast/etc. |
614 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
615 | static bool classofKind(Kind K) { return K == Namespace; } |
616 | static DeclContext *castToDeclContext(const NamespaceDecl *D) { |
617 | return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D)); |
618 | } |
619 | static NamespaceDecl *castFromDeclContext(const DeclContext *DC) { |
620 | return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC)); |
621 | } |
622 | }; |
623 | |
624 | /// ValueDecl - Represent the declaration of a variable (in which case it is |
625 | /// an lvalue) a function (in which case it is a function designator) or |
626 | /// an enum constant. |
627 | class ValueDecl : public NamedDecl { |
628 | QualType DeclType; |
629 | |
630 | void anchor() override; |
631 | |
632 | protected: |
633 | ValueDecl(Kind DK, DeclContext *DC, SourceLocation L, |
634 | DeclarationName N, QualType T) |
635 | : NamedDecl(DK, DC, L, N), DeclType(T) {} |
636 | |
637 | public: |
638 | QualType getType() const { return DeclType; } |
639 | void setType(QualType newType) { DeclType = newType; } |
640 | |
641 | /// \brief Determine whether this symbol is weakly-imported, |
642 | /// or declared with the weak or weak-ref attr. |
643 | bool isWeak() const; |
644 | |
645 | // Implement isa/cast/dyncast/etc. |
646 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
647 | static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; } |
648 | }; |
649 | |
650 | /// QualifierInfo - A struct with extended info about a syntactic |
651 | /// name qualifier, to be used for the case of out-of-line declarations. |
652 | struct QualifierInfo { |
653 | NestedNameSpecifierLoc QualifierLoc; |
654 | |
655 | /// NumTemplParamLists - The number of "outer" template parameter lists. |
656 | /// The count includes all of the template parameter lists that were matched |
657 | /// against the template-ids occurring into the NNS and possibly (in the |
658 | /// case of an explicit specialization) a final "template <>". |
659 | unsigned NumTemplParamLists = 0; |
660 | |
661 | /// TemplParamLists - A new-allocated array of size NumTemplParamLists, |
662 | /// containing pointers to the "outer" template parameter lists. |
663 | /// It includes all of the template parameter lists that were matched |
664 | /// against the template-ids occurring into the NNS and possibly (in the |
665 | /// case of an explicit specialization) a final "template <>". |
666 | TemplateParameterList** TemplParamLists = nullptr; |
667 | |
668 | QualifierInfo() = default; |
669 | QualifierInfo(const QualifierInfo &) = delete; |
670 | QualifierInfo& operator=(const QualifierInfo &) = delete; |
671 | |
672 | /// setTemplateParameterListsInfo - Sets info about "outer" template |
673 | /// parameter lists. |
674 | void setTemplateParameterListsInfo(ASTContext &Context, |
675 | ArrayRef<TemplateParameterList *> TPLists); |
676 | }; |
677 | |
678 | /// \brief Represents a ValueDecl that came out of a declarator. |
679 | /// Contains type source information through TypeSourceInfo. |
680 | class DeclaratorDecl : public ValueDecl { |
681 | // A struct representing both a TInfo and a syntactic qualifier, |
682 | // to be used for the (uncommon) case of out-of-line declarations. |
683 | struct ExtInfo : public QualifierInfo { |
684 | TypeSourceInfo *TInfo; |
685 | }; |
686 | |
687 | llvm::PointerUnion<TypeSourceInfo *, ExtInfo *> DeclInfo; |
688 | |
689 | /// InnerLocStart - The start of the source range for this declaration, |
690 | /// ignoring outer template declarations. |
691 | SourceLocation InnerLocStart; |
692 | |
693 | bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); } |
694 | ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); } |
695 | const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); } |
696 | |
697 | protected: |
698 | DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L, |
699 | DeclarationName N, QualType T, TypeSourceInfo *TInfo, |
700 | SourceLocation StartL) |
701 | : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {} |
702 | |
703 | public: |
704 | friend class ASTDeclReader; |
705 | friend class ASTDeclWriter; |
706 | |
707 | TypeSourceInfo *getTypeSourceInfo() const { |
708 | return hasExtInfo() |
709 | ? getExtInfo()->TInfo |
710 | : DeclInfo.get<TypeSourceInfo*>(); |
711 | } |
712 | |
713 | void setTypeSourceInfo(TypeSourceInfo *TI) { |
714 | if (hasExtInfo()) |
715 | getExtInfo()->TInfo = TI; |
716 | else |
717 | DeclInfo = TI; |
718 | } |
719 | |
720 | /// getInnerLocStart - Return SourceLocation representing start of source |
721 | /// range ignoring outer template declarations. |
722 | SourceLocation getInnerLocStart() const { return InnerLocStart; } |
723 | void setInnerLocStart(SourceLocation L) { InnerLocStart = L; } |
724 | |
725 | /// getOuterLocStart - Return SourceLocation representing start of source |
726 | /// range taking into account any outer template declarations. |
727 | SourceLocation getOuterLocStart() const; |
728 | |
729 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
730 | |
731 | SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { |
732 | return getOuterLocStart(); |
733 | } |
734 | |
735 | /// \brief Retrieve the nested-name-specifier that qualifies the name of this |
736 | /// declaration, if it was present in the source. |
737 | NestedNameSpecifier *getQualifier() const { |
738 | return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier() |
739 | : nullptr; |
740 | } |
741 | |
742 | /// \brief Retrieve the nested-name-specifier (with source-location |
743 | /// information) that qualifies the name of this declaration, if it was |
744 | /// present in the source. |
745 | NestedNameSpecifierLoc getQualifierLoc() const { |
746 | return hasExtInfo() ? getExtInfo()->QualifierLoc |
747 | : NestedNameSpecifierLoc(); |
748 | } |
749 | |
750 | void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc); |
751 | |
752 | unsigned getNumTemplateParameterLists() const { |
753 | return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0; |
754 | } |
755 | |
756 | TemplateParameterList *getTemplateParameterList(unsigned index) const { |
757 | assert(index < getNumTemplateParameterLists())(static_cast <bool> (index < getNumTemplateParameterLists ()) ? void (0) : __assert_fail ("index < getNumTemplateParameterLists()" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 757, __extension__ __PRETTY_FUNCTION__)); |
758 | return getExtInfo()->TemplParamLists[index]; |
759 | } |
760 | |
761 | void setTemplateParameterListsInfo(ASTContext &Context, |
762 | ArrayRef<TemplateParameterList *> TPLists); |
763 | |
764 | SourceLocation getTypeSpecStartLoc() const; |
765 | |
766 | // Implement isa/cast/dyncast/etc. |
767 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
768 | static bool classofKind(Kind K) { |
769 | return K >= firstDeclarator && K <= lastDeclarator; |
770 | } |
771 | }; |
772 | |
773 | /// \brief Structure used to store a statement, the constant value to |
774 | /// which it was evaluated (if any), and whether or not the statement |
775 | /// is an integral constant expression (if known). |
776 | struct EvaluatedStmt { |
777 | /// \brief Whether this statement was already evaluated. |
778 | bool WasEvaluated : 1; |
779 | |
780 | /// \brief Whether this statement is being evaluated. |
781 | bool IsEvaluating : 1; |
782 | |
783 | /// \brief Whether we already checked whether this statement was an |
784 | /// integral constant expression. |
785 | bool CheckedICE : 1; |
786 | |
787 | /// \brief Whether we are checking whether this statement is an |
788 | /// integral constant expression. |
789 | bool CheckingICE : 1; |
790 | |
791 | /// \brief Whether this statement is an integral constant expression, |
792 | /// or in C++11, whether the statement is a constant expression. Only |
793 | /// valid if CheckedICE is true. |
794 | bool IsICE : 1; |
795 | |
796 | Stmt *Value; |
797 | APValue Evaluated; |
798 | |
799 | EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false), |
800 | CheckingICE(false), IsICE(false) {} |
801 | |
802 | }; |
803 | |
804 | /// VarDecl - An instance of this class is created to represent a variable |
805 | /// declaration or definition. |
806 | class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> { |
807 | public: |
808 | /// \brief Initialization styles. |
809 | enum InitializationStyle { |
810 | /// C-style initialization with assignment |
811 | CInit, |
812 | |
813 | /// Call-style initialization (C++98) |
814 | CallInit, |
815 | |
816 | /// Direct list-initialization (C++11) |
817 | ListInit |
818 | }; |
819 | |
820 | /// \brief Kinds of thread-local storage. |
821 | enum TLSKind { |
822 | /// Not a TLS variable. |
823 | TLS_None, |
824 | |
825 | /// TLS with a known-constant initializer. |
826 | TLS_Static, |
827 | |
828 | /// TLS with a dynamic initializer. |
829 | TLS_Dynamic |
830 | }; |
831 | |
832 | /// getStorageClassSpecifierString - Return the string used to |
833 | /// specify the storage class \p SC. |
834 | /// |
835 | /// It is illegal to call this function with SC == None. |
836 | static const char *getStorageClassSpecifierString(StorageClass SC); |
837 | |
838 | protected: |
839 | // A pointer union of Stmt * and EvaluatedStmt *. When an EvaluatedStmt, we |
840 | // have allocated the auxiliary struct of information there. |
841 | // |
842 | // TODO: It is a bit unfortunate to use a PointerUnion inside the VarDecl for |
843 | // this as *many* VarDecls are ParmVarDecls that don't have default |
844 | // arguments. We could save some space by moving this pointer union to be |
845 | // allocated in trailing space when necessary. |
846 | using InitType = llvm::PointerUnion<Stmt *, EvaluatedStmt *>; |
847 | |
848 | /// \brief The initializer for this variable or, for a ParmVarDecl, the |
849 | /// C++ default argument. |
850 | mutable InitType Init; |
851 | |
852 | private: |
853 | friend class ASTDeclReader; |
854 | friend class ASTNodeImporter; |
855 | friend class StmtIteratorBase; |
856 | |
857 | class VarDeclBitfields { |
858 | friend class ASTDeclReader; |
859 | friend class VarDecl; |
860 | |
861 | unsigned SClass : 3; |
862 | unsigned TSCSpec : 2; |
863 | unsigned InitStyle : 2; |
864 | }; |
865 | enum { NumVarDeclBits = 7 }; |
866 | |
867 | protected: |
868 | enum { NumParameterIndexBits = 8 }; |
869 | |
870 | enum DefaultArgKind { |
871 | DAK_None, |
872 | DAK_Unparsed, |
873 | DAK_Uninstantiated, |
874 | DAK_Normal |
875 | }; |
876 | |
877 | class ParmVarDeclBitfields { |
878 | friend class ASTDeclReader; |
879 | friend class ParmVarDecl; |
880 | |
881 | unsigned : NumVarDeclBits; |
882 | |
883 | /// Whether this parameter inherits a default argument from a |
884 | /// prior declaration. |
885 | unsigned HasInheritedDefaultArg : 1; |
886 | |
887 | /// Describes the kind of default argument for this parameter. By default |
888 | /// this is none. If this is normal, then the default argument is stored in |
889 | /// the \c VarDecl initializer expression unless we were unable to parse |
890 | /// (even an invalid) expression for the default argument. |
891 | unsigned DefaultArgKind : 2; |
892 | |
893 | /// Whether this parameter undergoes K&R argument promotion. |
894 | unsigned IsKNRPromoted : 1; |
895 | |
896 | /// Whether this parameter is an ObjC method parameter or not. |
897 | unsigned IsObjCMethodParam : 1; |
898 | |
899 | /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier. |
900 | /// Otherwise, the number of function parameter scopes enclosing |
901 | /// the function parameter scope in which this parameter was |
902 | /// declared. |
903 | unsigned ScopeDepthOrObjCQuals : 7; |
904 | |
905 | /// The number of parameters preceding this parameter in the |
906 | /// function parameter scope in which it was declared. |
907 | unsigned ParameterIndex : NumParameterIndexBits; |
908 | }; |
909 | |
910 | class NonParmVarDeclBitfields { |
911 | friend class ASTDeclReader; |
912 | friend class ImplicitParamDecl; |
913 | friend class VarDecl; |
914 | |
915 | unsigned : NumVarDeclBits; |
916 | |
917 | // FIXME: We need something similar to CXXRecordDecl::DefinitionData. |
918 | /// \brief Whether this variable is a definition which was demoted due to |
919 | /// module merge. |
920 | unsigned IsThisDeclarationADemotedDefinition : 1; |
921 | |
922 | /// \brief Whether this variable is the exception variable in a C++ catch |
923 | /// or an Objective-C @catch statement. |
924 | unsigned ExceptionVar : 1; |
925 | |
926 | /// \brief Whether this local variable could be allocated in the return |
927 | /// slot of its function, enabling the named return value optimization |
928 | /// (NRVO). |
929 | unsigned NRVOVariable : 1; |
930 | |
931 | /// \brief Whether this variable is the for-range-declaration in a C++0x |
932 | /// for-range statement. |
933 | unsigned CXXForRangeDecl : 1; |
934 | |
935 | /// \brief Whether this variable is an ARC pseudo-__strong |
936 | /// variable; see isARCPseudoStrong() for details. |
937 | unsigned ARCPseudoStrong : 1; |
938 | |
939 | /// \brief Whether this variable is (C++1z) inline. |
940 | unsigned IsInline : 1; |
941 | |
942 | /// \brief Whether this variable has (C++1z) inline explicitly specified. |
943 | unsigned IsInlineSpecified : 1; |
944 | |
945 | /// \brief Whether this variable is (C++0x) constexpr. |
946 | unsigned IsConstexpr : 1; |
947 | |
948 | /// \brief Whether this variable is the implicit variable for a lambda |
949 | /// init-capture. |
950 | unsigned IsInitCapture : 1; |
951 | |
952 | /// \brief Whether this local extern variable's previous declaration was |
953 | /// declared in the same block scope. This controls whether we should merge |
954 | /// the type of this declaration with its previous declaration. |
955 | unsigned PreviousDeclInSameBlockScope : 1; |
956 | |
957 | /// Defines kind of the ImplicitParamDecl: 'this', 'self', 'vtt', '_cmd' or |
958 | /// something else. |
959 | unsigned ImplicitParamKind : 3; |
960 | }; |
961 | |
962 | union { |
963 | unsigned AllBits; |
964 | VarDeclBitfields VarDeclBits; |
965 | ParmVarDeclBitfields ParmVarDeclBits; |
966 | NonParmVarDeclBitfields NonParmVarDeclBits; |
967 | }; |
968 | |
969 | VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
970 | SourceLocation IdLoc, IdentifierInfo *Id, QualType T, |
971 | TypeSourceInfo *TInfo, StorageClass SC); |
972 | |
973 | using redeclarable_base = Redeclarable<VarDecl>; |
974 | |
975 | VarDecl *getNextRedeclarationImpl() override { |
976 | return getNextRedeclaration(); |
977 | } |
978 | |
979 | VarDecl *getPreviousDeclImpl() override { |
980 | return getPreviousDecl(); |
981 | } |
982 | |
983 | VarDecl *getMostRecentDeclImpl() override { |
984 | return getMostRecentDecl(); |
985 | } |
986 | |
987 | public: |
988 | using redecl_range = redeclarable_base::redecl_range; |
989 | using redecl_iterator = redeclarable_base::redecl_iterator; |
990 | |
991 | using redeclarable_base::redecls_begin; |
992 | using redeclarable_base::redecls_end; |
993 | using redeclarable_base::redecls; |
994 | using redeclarable_base::getPreviousDecl; |
995 | using redeclarable_base::getMostRecentDecl; |
996 | using redeclarable_base::isFirstDecl; |
997 | |
998 | static VarDecl *Create(ASTContext &C, DeclContext *DC, |
999 | SourceLocation StartLoc, SourceLocation IdLoc, |
1000 | IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, |
1001 | StorageClass S); |
1002 | |
1003 | static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
1004 | |
1005 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
1006 | |
1007 | /// \brief Returns the storage class as written in the source. For the |
1008 | /// computed linkage of symbol, see getLinkage. |
1009 | StorageClass getStorageClass() const { |
1010 | return (StorageClass) VarDeclBits.SClass; |
1011 | } |
1012 | void setStorageClass(StorageClass SC); |
1013 | |
1014 | void setTSCSpec(ThreadStorageClassSpecifier TSC) { |
1015 | VarDeclBits.TSCSpec = TSC; |
1016 | assert(VarDeclBits.TSCSpec == TSC && "truncation")(static_cast <bool> (VarDeclBits.TSCSpec == TSC && "truncation") ? void (0) : __assert_fail ("VarDeclBits.TSCSpec == TSC && \"truncation\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 1016, __extension__ __PRETTY_FUNCTION__)); |
1017 | } |
1018 | ThreadStorageClassSpecifier getTSCSpec() const { |
1019 | return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec); |
1020 | } |
1021 | TLSKind getTLSKind() const; |
1022 | |
1023 | /// hasLocalStorage - Returns true if a variable with function scope |
1024 | /// is a non-static local variable. |
1025 | bool hasLocalStorage() const { |
1026 | if (getStorageClass() == SC_None) { |
1027 | // OpenCL v1.2 s6.5.3: The __constant or constant address space name is |
1028 | // used to describe variables allocated in global memory and which are |
1029 | // accessed inside a kernel(s) as read-only variables. As such, variables |
1030 | // in constant address space cannot have local storage. |
1031 | if (getType().getAddressSpace() == LangAS::opencl_constant) |
1032 | return false; |
1033 | // Second check is for C++11 [dcl.stc]p4. |
1034 | return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified; |
1035 | } |
1036 | |
1037 | // Global Named Register (GNU extension) |
1038 | if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm()) |
1039 | return false; |
1040 | |
1041 | // Return true for: Auto, Register. |
1042 | // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal. |
1043 | |
1044 | return getStorageClass() >= SC_Auto; |
1045 | } |
1046 | |
1047 | /// isStaticLocal - Returns true if a variable with function scope is a |
1048 | /// static local variable. |
1049 | bool isStaticLocal() const { |
1050 | return (getStorageClass() == SC_Static || |
1051 | // C++11 [dcl.stc]p4 |
1052 | (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local)) |
1053 | && !isFileVarDecl(); |
1054 | } |
1055 | |
1056 | /// \brief Returns true if a variable has extern or __private_extern__ |
1057 | /// storage. |
1058 | bool hasExternalStorage() const { |
1059 | return getStorageClass() == SC_Extern || |
1060 | getStorageClass() == SC_PrivateExtern; |
1061 | } |
1062 | |
1063 | /// \brief Returns true for all variables that do not have local storage. |
1064 | /// |
1065 | /// This includes all global variables as well as static variables declared |
1066 | /// within a function. |
1067 | bool hasGlobalStorage() const { return !hasLocalStorage(); } |
1068 | |
1069 | /// \brief Get the storage duration of this variable, per C++ [basic.stc]. |
1070 | StorageDuration getStorageDuration() const { |
1071 | return hasLocalStorage() ? SD_Automatic : |
1072 | getTSCSpec() ? SD_Thread : SD_Static; |
1073 | } |
1074 | |
1075 | /// \brief Compute the language linkage. |
1076 | LanguageLinkage getLanguageLinkage() const; |
1077 | |
1078 | /// \brief Determines whether this variable is a variable with |
1079 | /// external, C linkage. |
1080 | bool isExternC() const; |
1081 | |
1082 | /// \brief Determines whether this variable's context is, or is nested within, |
1083 | /// a C++ extern "C" linkage spec. |
1084 | bool isInExternCContext() const; |
1085 | |
1086 | /// \brief Determines whether this variable's context is, or is nested within, |
1087 | /// a C++ extern "C++" linkage spec. |
1088 | bool isInExternCXXContext() const; |
1089 | |
1090 | /// isLocalVarDecl - Returns true for local variable declarations |
1091 | /// other than parameters. Note that this includes static variables |
1092 | /// inside of functions. It also includes variables inside blocks. |
1093 | /// |
1094 | /// void foo() { int x; static int y; extern int z; } |
1095 | bool isLocalVarDecl() const { |
1096 | if (getKind() != Decl::Var && getKind() != Decl::Decomposition) |
1097 | return false; |
1098 | if (const DeclContext *DC = getLexicalDeclContext()) |
1099 | return DC->getRedeclContext()->isFunctionOrMethod(); |
1100 | return false; |
1101 | } |
1102 | |
1103 | /// \brief Similar to isLocalVarDecl but also includes parameters. |
1104 | bool isLocalVarDeclOrParm() const { |
1105 | return isLocalVarDecl() || getKind() == Decl::ParmVar; |
1106 | } |
1107 | |
1108 | /// isFunctionOrMethodVarDecl - Similar to isLocalVarDecl, but |
1109 | /// excludes variables declared in blocks. |
1110 | bool isFunctionOrMethodVarDecl() const { |
1111 | if (getKind() != Decl::Var && getKind() != Decl::Decomposition) |
1112 | return false; |
1113 | const DeclContext *DC = getLexicalDeclContext()->getRedeclContext(); |
1114 | return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block; |
1115 | } |
1116 | |
1117 | /// \brief Determines whether this is a static data member. |
1118 | /// |
1119 | /// This will only be true in C++, and applies to, e.g., the |
1120 | /// variable 'x' in: |
1121 | /// \code |
1122 | /// struct S { |
1123 | /// static int x; |
1124 | /// }; |
1125 | /// \endcode |
1126 | bool isStaticDataMember() const { |
1127 | // If it wasn't static, it would be a FieldDecl. |
1128 | return getKind() != Decl::ParmVar && getDeclContext()->isRecord(); |
1129 | } |
1130 | |
1131 | VarDecl *getCanonicalDecl() override; |
1132 | const VarDecl *getCanonicalDecl() const { |
1133 | return const_cast<VarDecl*>(this)->getCanonicalDecl(); |
1134 | } |
1135 | |
1136 | enum DefinitionKind { |
1137 | /// This declaration is only a declaration. |
1138 | DeclarationOnly, |
1139 | |
1140 | /// This declaration is a tentative definition. |
1141 | TentativeDefinition, |
1142 | |
1143 | /// This declaration is definitely a definition. |
1144 | Definition |
1145 | }; |
1146 | |
1147 | /// \brief Check whether this declaration is a definition. If this could be |
1148 | /// a tentative definition (in C), don't check whether there's an overriding |
1149 | /// definition. |
1150 | DefinitionKind isThisDeclarationADefinition(ASTContext &) const; |
1151 | DefinitionKind isThisDeclarationADefinition() const { |
1152 | return isThisDeclarationADefinition(getASTContext()); |
1153 | } |
1154 | |
1155 | /// \brief Check whether this variable is defined in this |
1156 | /// translation unit. |
1157 | DefinitionKind hasDefinition(ASTContext &) const; |
1158 | DefinitionKind hasDefinition() const { |
1159 | return hasDefinition(getASTContext()); |
1160 | } |
1161 | |
1162 | /// \brief Get the tentative definition that acts as the real definition in |
1163 | /// a TU. Returns null if there is a proper definition available. |
1164 | VarDecl *getActingDefinition(); |
1165 | const VarDecl *getActingDefinition() const { |
1166 | return const_cast<VarDecl*>(this)->getActingDefinition(); |
1167 | } |
1168 | |
1169 | /// \brief Get the real (not just tentative) definition for this declaration. |
1170 | VarDecl *getDefinition(ASTContext &); |
1171 | const VarDecl *getDefinition(ASTContext &C) const { |
1172 | return const_cast<VarDecl*>(this)->getDefinition(C); |
1173 | } |
1174 | VarDecl *getDefinition() { |
1175 | return getDefinition(getASTContext()); |
1176 | } |
1177 | const VarDecl *getDefinition() const { |
1178 | return const_cast<VarDecl*>(this)->getDefinition(); |
1179 | } |
1180 | |
1181 | /// \brief Determine whether this is or was instantiated from an out-of-line |
1182 | /// definition of a static data member. |
1183 | bool isOutOfLine() const override; |
1184 | |
1185 | /// isFileVarDecl - Returns true for file scoped variable declaration. |
1186 | bool isFileVarDecl() const { |
1187 | Kind K = getKind(); |
1188 | if (K == ParmVar || K == ImplicitParam) |
1189 | return false; |
1190 | |
1191 | if (getLexicalDeclContext()->getRedeclContext()->isFileContext()) |
1192 | return true; |
1193 | |
1194 | if (isStaticDataMember()) |
1195 | return true; |
1196 | |
1197 | return false; |
1198 | } |
1199 | |
1200 | /// getAnyInitializer - Get the initializer for this variable, no matter which |
1201 | /// declaration it is attached to. |
1202 | const Expr *getAnyInitializer() const { |
1203 | const VarDecl *D; |
1204 | return getAnyInitializer(D); |
1205 | } |
1206 | |
1207 | /// getAnyInitializer - Get the initializer for this variable, no matter which |
1208 | /// declaration it is attached to. Also get that declaration. |
1209 | const Expr *getAnyInitializer(const VarDecl *&D) const; |
1210 | |
1211 | bool hasInit() const; |
1212 | const Expr *getInit() const { |
1213 | return const_cast<VarDecl *>(this)->getInit(); |
1214 | } |
1215 | Expr *getInit(); |
1216 | |
1217 | /// \brief Retrieve the address of the initializer expression. |
1218 | Stmt **getInitAddress(); |
1219 | |
1220 | void setInit(Expr *I); |
1221 | |
1222 | /// \brief Determine whether this variable's value can be used in a |
1223 | /// constant expression, according to the relevant language standard. |
1224 | /// This only checks properties of the declaration, and does not check |
1225 | /// whether the initializer is in fact a constant expression. |
1226 | bool isUsableInConstantExpressions(ASTContext &C) const; |
1227 | |
1228 | EvaluatedStmt *ensureEvaluatedStmt() const; |
1229 | |
1230 | /// \brief Attempt to evaluate the value of the initializer attached to this |
1231 | /// declaration, and produce notes explaining why it cannot be evaluated or is |
1232 | /// not a constant expression. Returns a pointer to the value if evaluation |
1233 | /// succeeded, 0 otherwise. |
1234 | APValue *evaluateValue() const; |
1235 | APValue *evaluateValue(SmallVectorImpl<PartialDiagnosticAt> &Notes) const; |
1236 | |
1237 | /// \brief Return the already-evaluated value of this variable's |
1238 | /// initializer, or NULL if the value is not yet known. Returns pointer |
1239 | /// to untyped APValue if the value could not be evaluated. |
1240 | APValue *getEvaluatedValue() const; |
1241 | |
1242 | /// \brief Determines whether it is already known whether the |
1243 | /// initializer is an integral constant expression or not. |
1244 | bool isInitKnownICE() const; |
1245 | |
1246 | /// \brief Determines whether the initializer is an integral constant |
1247 | /// expression, or in C++11, whether the initializer is a constant |
1248 | /// expression. |
1249 | /// |
1250 | /// \pre isInitKnownICE() |
1251 | bool isInitICE() const; |
1252 | |
1253 | /// \brief Determine whether the value of the initializer attached to this |
1254 | /// declaration is an integral constant expression. |
1255 | bool checkInitIsICE() const; |
1256 | |
1257 | void setInitStyle(InitializationStyle Style) { |
1258 | VarDeclBits.InitStyle = Style; |
1259 | } |
1260 | |
1261 | /// \brief The style of initialization for this declaration. |
1262 | /// |
1263 | /// C-style initialization is "int x = 1;". Call-style initialization is |
1264 | /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be |
1265 | /// the expression inside the parens or a "ClassType(a,b,c)" class constructor |
1266 | /// expression for class types. List-style initialization is C++11 syntax, |
1267 | /// e.g. "int x{1};". Clients can distinguish between different forms of |
1268 | /// initialization by checking this value. In particular, "int x = {1};" is |
1269 | /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the |
1270 | /// Init expression in all three cases is an InitListExpr. |
1271 | InitializationStyle getInitStyle() const { |
1272 | return static_cast<InitializationStyle>(VarDeclBits.InitStyle); |
1273 | } |
1274 | |
1275 | /// \brief Whether the initializer is a direct-initializer (list or call). |
1276 | bool isDirectInit() const { |
1277 | return getInitStyle() != CInit; |
1278 | } |
1279 | |
1280 | /// \brief If this definition should pretend to be a declaration. |
1281 | bool isThisDeclarationADemotedDefinition() const { |
1282 | return isa<ParmVarDecl>(this) ? false : |
1283 | NonParmVarDeclBits.IsThisDeclarationADemotedDefinition; |
1284 | } |
1285 | |
1286 | /// \brief This is a definition which should be demoted to a declaration. |
1287 | /// |
1288 | /// In some cases (mostly module merging) we can end up with two visible |
1289 | /// definitions one of which needs to be demoted to a declaration to keep |
1290 | /// the AST invariants. |
1291 | void demoteThisDefinitionToDeclaration() { |
1292 | assert(isThisDeclarationADefinition() && "Not a definition!")(static_cast <bool> (isThisDeclarationADefinition() && "Not a definition!") ? void (0) : __assert_fail ("isThisDeclarationADefinition() && \"Not a definition!\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 1292, __extension__ __PRETTY_FUNCTION__)); |
1293 | assert(!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!")(static_cast <bool> (!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!") ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this) && \"Cannot demote ParmVarDecls!\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 1293, __extension__ __PRETTY_FUNCTION__)); |
1294 | NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1; |
1295 | } |
1296 | |
1297 | /// \brief Determine whether this variable is the exception variable in a |
1298 | /// C++ catch statememt or an Objective-C \@catch statement. |
1299 | bool isExceptionVariable() const { |
1300 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar; |
1301 | } |
1302 | void setExceptionVariable(bool EV) { |
1303 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 1303, __extension__ __PRETTY_FUNCTION__)); |
1304 | NonParmVarDeclBits.ExceptionVar = EV; |
1305 | } |
1306 | |
1307 | /// \brief Determine whether this local variable can be used with the named |
1308 | /// return value optimization (NRVO). |
1309 | /// |
1310 | /// The named return value optimization (NRVO) works by marking certain |
1311 | /// non-volatile local variables of class type as NRVO objects. These |
1312 | /// locals can be allocated within the return slot of their containing |
1313 | /// function, in which case there is no need to copy the object to the |
1314 | /// return slot when returning from the function. Within the function body, |
1315 | /// each return that returns the NRVO object will have this variable as its |
1316 | /// NRVO candidate. |
1317 | bool isNRVOVariable() const { |
1318 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable; |
1319 | } |
1320 | void setNRVOVariable(bool NRVO) { |
1321 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 1321, __extension__ __PRETTY_FUNCTION__)); |
1322 | NonParmVarDeclBits.NRVOVariable = NRVO; |
1323 | } |
1324 | |
1325 | /// \brief Determine whether this variable is the for-range-declaration in |
1326 | /// a C++0x for-range statement. |
1327 | bool isCXXForRangeDecl() const { |
1328 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl; |
1329 | } |
1330 | void setCXXForRangeDecl(bool FRD) { |
1331 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 1331, __extension__ __PRETTY_FUNCTION__)); |
1332 | NonParmVarDeclBits.CXXForRangeDecl = FRD; |
1333 | } |
1334 | |
1335 | /// \brief Determine whether this variable is an ARC pseudo-__strong |
1336 | /// variable. A pseudo-__strong variable has a __strong-qualified |
1337 | /// type but does not actually retain the object written into it. |
1338 | /// Generally such variables are also 'const' for safety. |
1339 | bool isARCPseudoStrong() const { |
1340 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ARCPseudoStrong; |
1341 | } |
1342 | void setARCPseudoStrong(bool ps) { |
1343 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 1343, __extension__ __PRETTY_FUNCTION__)); |
1344 | NonParmVarDeclBits.ARCPseudoStrong = ps; |
1345 | } |
1346 | |
1347 | /// Whether this variable is (C++1z) inline. |
1348 | bool isInline() const { |
1349 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInline; |
1350 | } |
1351 | bool isInlineSpecified() const { |
1352 | return isa<ParmVarDecl>(this) ? false |
1353 | : NonParmVarDeclBits.IsInlineSpecified; |
1354 | } |
1355 | void setInlineSpecified() { |
1356 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 1356, __extension__ __PRETTY_FUNCTION__)); |
1357 | NonParmVarDeclBits.IsInline = true; |
1358 | NonParmVarDeclBits.IsInlineSpecified = true; |
1359 | } |
1360 | void setImplicitlyInline() { |
1361 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 1361, __extension__ __PRETTY_FUNCTION__)); |
1362 | NonParmVarDeclBits.IsInline = true; |
1363 | } |
1364 | |
1365 | /// Whether this variable is (C++11) constexpr. |
1366 | bool isConstexpr() const { |
1367 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsConstexpr; |
1368 | } |
1369 | void setConstexpr(bool IC) { |
1370 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 1370, __extension__ __PRETTY_FUNCTION__)); |
1371 | NonParmVarDeclBits.IsConstexpr = IC; |
1372 | } |
1373 | |
1374 | /// Whether this variable is the implicit variable for a lambda init-capture. |
1375 | bool isInitCapture() const { |
1376 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInitCapture; |
1377 | } |
1378 | void setInitCapture(bool IC) { |
1379 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 1379, __extension__ __PRETTY_FUNCTION__)); |
1380 | NonParmVarDeclBits.IsInitCapture = IC; |
1381 | } |
1382 | |
1383 | /// Whether this local extern variable declaration's previous declaration |
1384 | /// was declared in the same block scope. Only correct in C++. |
1385 | bool isPreviousDeclInSameBlockScope() const { |
1386 | return isa<ParmVarDecl>(this) |
1387 | ? false |
1388 | : NonParmVarDeclBits.PreviousDeclInSameBlockScope; |
1389 | } |
1390 | void setPreviousDeclInSameBlockScope(bool Same) { |
1391 | assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 1391, __extension__ __PRETTY_FUNCTION__)); |
1392 | NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same; |
1393 | } |
1394 | |
1395 | /// \brief Retrieve the variable declaration from which this variable could |
1396 | /// be instantiated, if it is an instantiation (rather than a non-template). |
1397 | VarDecl *getTemplateInstantiationPattern() const; |
1398 | |
1399 | /// \brief If this variable is an instantiated static data member of a |
1400 | /// class template specialization, returns the templated static data member |
1401 | /// from which it was instantiated. |
1402 | VarDecl *getInstantiatedFromStaticDataMember() const; |
1403 | |
1404 | /// \brief If this variable is an instantiation of a variable template or a |
1405 | /// static data member of a class template, determine what kind of |
1406 | /// template specialization or instantiation this is. |
1407 | TemplateSpecializationKind getTemplateSpecializationKind() const; |
1408 | |
1409 | /// \brief If this variable is an instantiation of a variable template or a |
1410 | /// static data member of a class template, determine its point of |
1411 | /// instantiation. |
1412 | SourceLocation getPointOfInstantiation() const; |
1413 | |
1414 | /// \brief If this variable is an instantiation of a static data member of a |
1415 | /// class template specialization, retrieves the member specialization |
1416 | /// information. |
1417 | MemberSpecializationInfo *getMemberSpecializationInfo() const; |
1418 | |
1419 | /// \brief For a static data member that was instantiated from a static |
1420 | /// data member of a class template, set the template specialiation kind. |
1421 | void setTemplateSpecializationKind(TemplateSpecializationKind TSK, |
1422 | SourceLocation PointOfInstantiation = SourceLocation()); |
1423 | |
1424 | /// \brief Specify that this variable is an instantiation of the |
1425 | /// static data member VD. |
1426 | void setInstantiationOfStaticDataMember(VarDecl *VD, |
1427 | TemplateSpecializationKind TSK); |
1428 | |
1429 | /// \brief Retrieves the variable template that is described by this |
1430 | /// variable declaration. |
1431 | /// |
1432 | /// Every variable template is represented as a VarTemplateDecl and a |
1433 | /// VarDecl. The former contains template properties (such as |
1434 | /// the template parameter lists) while the latter contains the |
1435 | /// actual description of the template's |
1436 | /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the |
1437 | /// VarDecl that from a VarTemplateDecl, while |
1438 | /// getDescribedVarTemplate() retrieves the VarTemplateDecl from |
1439 | /// a VarDecl. |
1440 | VarTemplateDecl *getDescribedVarTemplate() const; |
1441 | |
1442 | void setDescribedVarTemplate(VarTemplateDecl *Template); |
1443 | |
1444 | // Implement isa/cast/dyncast/etc. |
1445 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
1446 | static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; } |
1447 | }; |
1448 | |
1449 | class ImplicitParamDecl : public VarDecl { |
1450 | void anchor() override; |
1451 | |
1452 | public: |
1453 | /// Defines the kind of the implicit parameter: is this an implicit parameter |
1454 | /// with pointer to 'this', 'self', '_cmd', virtual table pointers, captured |
1455 | /// context or something else. |
1456 | enum ImplicitParamKind : unsigned { |
1457 | /// Parameter for Objective-C 'self' argument |
1458 | ObjCSelf, |
1459 | |
1460 | /// Parameter for Objective-C '_cmd' argument |
1461 | ObjCCmd, |
1462 | |
1463 | /// Parameter for C++ 'this' argument |
1464 | CXXThis, |
1465 | |
1466 | /// Parameter for C++ virtual table pointers |
1467 | CXXVTT, |
1468 | |
1469 | /// Parameter for captured context |
1470 | CapturedContext, |
1471 | |
1472 | /// Other implicit parameter |
1473 | Other, |
1474 | }; |
1475 | |
1476 | /// Create implicit parameter. |
1477 | static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC, |
1478 | SourceLocation IdLoc, IdentifierInfo *Id, |
1479 | QualType T, ImplicitParamKind ParamKind); |
1480 | static ImplicitParamDecl *Create(ASTContext &C, QualType T, |
1481 | ImplicitParamKind ParamKind); |
1482 | |
1483 | static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
1484 | |
1485 | ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, |
1486 | IdentifierInfo *Id, QualType Type, |
1487 | ImplicitParamKind ParamKind) |
1488 | : VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type, |
1489 | /*TInfo=*/nullptr, SC_None) { |
1490 | NonParmVarDeclBits.ImplicitParamKind = ParamKind; |
1491 | setImplicit(); |
1492 | } |
1493 | |
1494 | ImplicitParamDecl(ASTContext &C, QualType Type, ImplicitParamKind ParamKind) |
1495 | : VarDecl(ImplicitParam, C, /*DC=*/nullptr, SourceLocation(), |
1496 | SourceLocation(), /*Id=*/nullptr, Type, |
1497 | /*TInfo=*/nullptr, SC_None) { |
1498 | NonParmVarDeclBits.ImplicitParamKind = ParamKind; |
1499 | setImplicit(); |
1500 | } |
1501 | |
1502 | /// Returns the implicit parameter kind. |
1503 | ImplicitParamKind getParameterKind() const { |
1504 | return static_cast<ImplicitParamKind>(NonParmVarDeclBits.ImplicitParamKind); |
1505 | } |
1506 | |
1507 | // Implement isa/cast/dyncast/etc. |
1508 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
1509 | static bool classofKind(Kind K) { return K == ImplicitParam; } |
1510 | }; |
1511 | |
1512 | /// ParmVarDecl - Represents a parameter to a function. |
1513 | class ParmVarDecl : public VarDecl { |
1514 | public: |
1515 | enum { MaxFunctionScopeDepth = 255 }; |
1516 | enum { MaxFunctionScopeIndex = 255 }; |
1517 | |
1518 | protected: |
1519 | ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
1520 | SourceLocation IdLoc, IdentifierInfo *Id, QualType T, |
1521 | TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg) |
1522 | : VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) { |
1523 | assert(ParmVarDeclBits.HasInheritedDefaultArg == false)(static_cast <bool> (ParmVarDeclBits.HasInheritedDefaultArg == false) ? void (0) : __assert_fail ("ParmVarDeclBits.HasInheritedDefaultArg == false" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 1523, __extension__ __PRETTY_FUNCTION__)); |
1524 | assert(ParmVarDeclBits.DefaultArgKind == DAK_None)(static_cast <bool> (ParmVarDeclBits.DefaultArgKind == DAK_None ) ? void (0) : __assert_fail ("ParmVarDeclBits.DefaultArgKind == DAK_None" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 1524, __extension__ __PRETTY_FUNCTION__)); |
1525 | assert(ParmVarDeclBits.IsKNRPromoted == false)(static_cast <bool> (ParmVarDeclBits.IsKNRPromoted == false ) ? void (0) : __assert_fail ("ParmVarDeclBits.IsKNRPromoted == false" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 1525, __extension__ __PRETTY_FUNCTION__)); |
1526 | assert(ParmVarDeclBits.IsObjCMethodParam == false)(static_cast <bool> (ParmVarDeclBits.IsObjCMethodParam == false) ? void (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam == false" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 1526, __extension__ __PRETTY_FUNCTION__)); |
1527 | setDefaultArg(DefArg); |
1528 | } |
1529 | |
1530 | public: |
1531 | static ParmVarDecl *Create(ASTContext &C, DeclContext *DC, |
1532 | SourceLocation StartLoc, |
1533 | SourceLocation IdLoc, IdentifierInfo *Id, |
1534 | QualType T, TypeSourceInfo *TInfo, |
1535 | StorageClass S, Expr *DefArg); |
1536 | |
1537 | static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
1538 | |
1539 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
1540 | |
1541 | void setObjCMethodScopeInfo(unsigned parameterIndex) { |
1542 | ParmVarDeclBits.IsObjCMethodParam = true; |
1543 | setParameterIndex(parameterIndex); |
1544 | } |
1545 | |
1546 | void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) { |
1547 | assert(!ParmVarDeclBits.IsObjCMethodParam)(static_cast <bool> (!ParmVarDeclBits.IsObjCMethodParam ) ? void (0) : __assert_fail ("!ParmVarDeclBits.IsObjCMethodParam" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 1547, __extension__ __PRETTY_FUNCTION__)); |
1548 | |
1549 | ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth; |
1550 | assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth(static_cast <bool> (ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && "truncation!") ? void (0) : __assert_fail ("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 1551, __extension__ __PRETTY_FUNCTION__)) |
1551 | && "truncation!")(static_cast <bool> (ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && "truncation!") ? void (0) : __assert_fail ("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 1551, __extension__ __PRETTY_FUNCTION__)); |
1552 | |
1553 | setParameterIndex(parameterIndex); |
1554 | } |
1555 | |
1556 | bool isObjCMethodParameter() const { |
1557 | return ParmVarDeclBits.IsObjCMethodParam; |
1558 | } |
1559 | |
1560 | unsigned getFunctionScopeDepth() const { |
1561 | if (ParmVarDeclBits.IsObjCMethodParam) return 0; |
1562 | return ParmVarDeclBits.ScopeDepthOrObjCQuals; |
1563 | } |
1564 | |
1565 | /// Returns the index of this parameter in its prototype or method scope. |
1566 | unsigned getFunctionScopeIndex() const { |
1567 | return getParameterIndex(); |
1568 | } |
1569 | |
1570 | ObjCDeclQualifier getObjCDeclQualifier() const { |
1571 | if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None; |
1572 | return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals); |
1573 | } |
1574 | void setObjCDeclQualifier(ObjCDeclQualifier QTVal) { |
1575 | assert(ParmVarDeclBits.IsObjCMethodParam)(static_cast <bool> (ParmVarDeclBits.IsObjCMethodParam) ? void (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 1575, __extension__ __PRETTY_FUNCTION__)); |
1576 | ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal; |
1577 | } |
1578 | |
1579 | /// True if the value passed to this parameter must undergo |
1580 | /// K&R-style default argument promotion: |
1581 | /// |
1582 | /// C99 6.5.2.2. |
1583 | /// If the expression that denotes the called function has a type |
1584 | /// that does not include a prototype, the integer promotions are |
1585 | /// performed on each argument, and arguments that have type float |
1586 | /// are promoted to double. |
1587 | bool isKNRPromoted() const { |
1588 | return ParmVarDeclBits.IsKNRPromoted; |
1589 | } |
1590 | void setKNRPromoted(bool promoted) { |
1591 | ParmVarDeclBits.IsKNRPromoted = promoted; |
1592 | } |
1593 | |
1594 | Expr *getDefaultArg(); |
1595 | const Expr *getDefaultArg() const { |
1596 | return const_cast<ParmVarDecl *>(this)->getDefaultArg(); |
1597 | } |
1598 | |
1599 | void setDefaultArg(Expr *defarg); |
1600 | |
1601 | /// \brief Retrieve the source range that covers the entire default |
1602 | /// argument. |
1603 | SourceRange getDefaultArgRange() const; |
1604 | void setUninstantiatedDefaultArg(Expr *arg); |
1605 | Expr *getUninstantiatedDefaultArg(); |
1606 | const Expr *getUninstantiatedDefaultArg() const { |
1607 | return const_cast<ParmVarDecl *>(this)->getUninstantiatedDefaultArg(); |
1608 | } |
1609 | |
1610 | /// hasDefaultArg - Determines whether this parameter has a default argument, |
1611 | /// either parsed or not. |
1612 | bool hasDefaultArg() const; |
1613 | |
1614 | /// hasUnparsedDefaultArg - Determines whether this parameter has a |
1615 | /// default argument that has not yet been parsed. This will occur |
1616 | /// during the processing of a C++ class whose member functions have |
1617 | /// default arguments, e.g., |
1618 | /// @code |
1619 | /// class X { |
1620 | /// public: |
1621 | /// void f(int x = 17); // x has an unparsed default argument now |
1622 | /// }; // x has a regular default argument now |
1623 | /// @endcode |
1624 | bool hasUnparsedDefaultArg() const { |
1625 | return ParmVarDeclBits.DefaultArgKind == DAK_Unparsed; |
1626 | } |
1627 | |
1628 | bool hasUninstantiatedDefaultArg() const { |
1629 | return ParmVarDeclBits.DefaultArgKind == DAK_Uninstantiated; |
1630 | } |
1631 | |
1632 | /// setUnparsedDefaultArg - Specify that this parameter has an |
1633 | /// unparsed default argument. The argument will be replaced with a |
1634 | /// real default argument via setDefaultArg when the class |
1635 | /// definition enclosing the function declaration that owns this |
1636 | /// default argument is completed. |
1637 | void setUnparsedDefaultArg() { |
1638 | ParmVarDeclBits.DefaultArgKind = DAK_Unparsed; |
1639 | } |
1640 | |
1641 | bool hasInheritedDefaultArg() const { |
1642 | return ParmVarDeclBits.HasInheritedDefaultArg; |
1643 | } |
1644 | |
1645 | void setHasInheritedDefaultArg(bool I = true) { |
1646 | ParmVarDeclBits.HasInheritedDefaultArg = I; |
1647 | } |
1648 | |
1649 | QualType getOriginalType() const; |
1650 | |
1651 | /// \brief Determine whether this parameter is actually a function |
1652 | /// parameter pack. |
1653 | bool isParameterPack() const; |
1654 | |
1655 | /// setOwningFunction - Sets the function declaration that owns this |
1656 | /// ParmVarDecl. Since ParmVarDecls are often created before the |
1657 | /// FunctionDecls that own them, this routine is required to update |
1658 | /// the DeclContext appropriately. |
1659 | void setOwningFunction(DeclContext *FD) { setDeclContext(FD); } |
1660 | |
1661 | // Implement isa/cast/dyncast/etc. |
1662 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
1663 | static bool classofKind(Kind K) { return K == ParmVar; } |
1664 | |
1665 | private: |
1666 | enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 }; |
1667 | |
1668 | void setParameterIndex(unsigned parameterIndex) { |
1669 | if (parameterIndex >= ParameterIndexSentinel) { |
1670 | setParameterIndexLarge(parameterIndex); |
1671 | return; |
1672 | } |
1673 | |
1674 | ParmVarDeclBits.ParameterIndex = parameterIndex; |
1675 | assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!")(static_cast <bool> (ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!") ? void (0) : __assert_fail ("ParmVarDeclBits.ParameterIndex == parameterIndex && \"truncation!\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 1675, __extension__ __PRETTY_FUNCTION__)); |
1676 | } |
1677 | unsigned getParameterIndex() const { |
1678 | unsigned d = ParmVarDeclBits.ParameterIndex; |
1679 | return d == ParameterIndexSentinel ? getParameterIndexLarge() : d; |
1680 | } |
1681 | |
1682 | void setParameterIndexLarge(unsigned parameterIndex); |
1683 | unsigned getParameterIndexLarge() const; |
1684 | }; |
1685 | |
1686 | /// An instance of this class is created to represent a function declaration or |
1687 | /// definition. |
1688 | /// |
1689 | /// Since a given function can be declared several times in a program, |
1690 | /// there may be several FunctionDecls that correspond to that |
1691 | /// function. Only one of those FunctionDecls will be found when |
1692 | /// traversing the list of declarations in the context of the |
1693 | /// FunctionDecl (e.g., the translation unit); this FunctionDecl |
1694 | /// contains all of the information known about the function. Other, |
1695 | /// previous declarations of the function are available via the |
1696 | /// getPreviousDecl() chain. |
1697 | class FunctionDecl : public DeclaratorDecl, public DeclContext, |
1698 | public Redeclarable<FunctionDecl> { |
1699 | public: |
1700 | /// \brief The kind of templated function a FunctionDecl can be. |
1701 | enum TemplatedKind { |
1702 | TK_NonTemplate, |
1703 | TK_FunctionTemplate, |
1704 | TK_MemberSpecialization, |
1705 | TK_FunctionTemplateSpecialization, |
1706 | TK_DependentFunctionTemplateSpecialization |
1707 | }; |
1708 | |
1709 | private: |
1710 | /// ParamInfo - new[]'d array of pointers to VarDecls for the formal |
1711 | /// parameters of this function. This is null if a prototype or if there are |
1712 | /// no formals. |
1713 | ParmVarDecl **ParamInfo = nullptr; |
1714 | |
1715 | LazyDeclStmtPtr Body; |
1716 | |
1717 | // FIXME: This can be packed into the bitfields in DeclContext. |
1718 | // NOTE: VC++ packs bitfields poorly if the types differ. |
1719 | unsigned SClass : 3; |
1720 | unsigned IsInline : 1; |
1721 | unsigned IsInlineSpecified : 1; |
1722 | |
1723 | protected: |
1724 | // This is shared by CXXConstructorDecl, CXXConversionDecl, and |
1725 | // CXXDeductionGuideDecl. |
1726 | unsigned IsExplicitSpecified : 1; |
1727 | |
1728 | private: |
1729 | unsigned IsVirtualAsWritten : 1; |
1730 | unsigned IsPure : 1; |
1731 | unsigned HasInheritedPrototype : 1; |
1732 | unsigned HasWrittenPrototype : 1; |
1733 | unsigned IsDeleted : 1; |
1734 | unsigned IsTrivial : 1; // sunk from CXXMethodDecl |
1735 | unsigned IsDefaulted : 1; // sunk from CXXMethoDecl |
1736 | unsigned IsExplicitlyDefaulted : 1; //sunk from CXXMethodDecl |
1737 | unsigned HasImplicitReturnZero : 1; |
1738 | unsigned IsLateTemplateParsed : 1; |
1739 | unsigned IsConstexpr : 1; |
1740 | unsigned InstantiationIsPending : 1; |
1741 | |
1742 | /// \brief Indicates if the function uses __try. |
1743 | unsigned UsesSEHTry : 1; |
1744 | |
1745 | /// \brief Indicates if the function was a definition but its body was |
1746 | /// skipped. |
1747 | unsigned HasSkippedBody : 1; |
1748 | |
1749 | /// Indicates if the function declaration will have a body, once we're done |
1750 | /// parsing it. |
1751 | unsigned WillHaveBody : 1; |
1752 | |
1753 | protected: |
1754 | /// [C++17] Only used by CXXDeductionGuideDecl. Declared here to avoid |
1755 | /// increasing the size of CXXDeductionGuideDecl by the size of an unsigned |
1756 | /// int as opposed to adding a single bit to FunctionDecl. |
1757 | /// Indicates that the Deduction Guide is the implicitly generated 'copy |
1758 | /// deduction candidate' (is used during overload resolution). |
1759 | unsigned IsCopyDeductionCandidate : 1; |
1760 | |
1761 | private: |
1762 | |
1763 | /// Store the ODRHash after first calculation. |
1764 | unsigned HasODRHash : 1; |
1765 | unsigned ODRHash; |
1766 | |
1767 | /// \brief End part of this FunctionDecl's source range. |
1768 | /// |
1769 | /// We could compute the full range in getSourceRange(). However, when we're |
1770 | /// dealing with a function definition deserialized from a PCH/AST file, |
1771 | /// we can only compute the full range once the function body has been |
1772 | /// de-serialized, so it's far better to have the (sometimes-redundant) |
1773 | /// EndRangeLoc. |
1774 | SourceLocation EndRangeLoc; |
1775 | |
1776 | /// \brief The template or declaration that this declaration |
1777 | /// describes or was instantiated from, respectively. |
1778 | /// |
1779 | /// For non-templates, this value will be NULL. For function |
1780 | /// declarations that describe a function template, this will be a |
1781 | /// pointer to a FunctionTemplateDecl. For member functions |
1782 | /// of class template specializations, this will be a MemberSpecializationInfo |
1783 | /// pointer containing information about the specialization. |
1784 | /// For function template specializations, this will be a |
1785 | /// FunctionTemplateSpecializationInfo, which contains information about |
1786 | /// the template being specialized and the template arguments involved in |
1787 | /// that specialization. |
1788 | llvm::PointerUnion4<FunctionTemplateDecl *, |
1789 | MemberSpecializationInfo *, |
1790 | FunctionTemplateSpecializationInfo *, |
1791 | DependentFunctionTemplateSpecializationInfo *> |
1792 | TemplateOrSpecialization; |
1793 | |
1794 | /// Provides source/type location info for the declaration name embedded in |
1795 | /// the DeclaratorDecl base class. |
1796 | DeclarationNameLoc DNLoc; |
1797 | |
1798 | /// \brief Specify that this function declaration is actually a function |
1799 | /// template specialization. |
1800 | /// |
1801 | /// \param C the ASTContext. |
1802 | /// |
1803 | /// \param Template the function template that this function template |
1804 | /// specialization specializes. |
1805 | /// |
1806 | /// \param TemplateArgs the template arguments that produced this |
1807 | /// function template specialization from the template. |
1808 | /// |
1809 | /// \param InsertPos If non-NULL, the position in the function template |
1810 | /// specialization set where the function template specialization data will |
1811 | /// be inserted. |
1812 | /// |
1813 | /// \param TSK the kind of template specialization this is. |
1814 | /// |
1815 | /// \param TemplateArgsAsWritten location info of template arguments. |
1816 | /// |
1817 | /// \param PointOfInstantiation point at which the function template |
1818 | /// specialization was first instantiated. |
1819 | void setFunctionTemplateSpecialization(ASTContext &C, |
1820 | FunctionTemplateDecl *Template, |
1821 | const TemplateArgumentList *TemplateArgs, |
1822 | void *InsertPos, |
1823 | TemplateSpecializationKind TSK, |
1824 | const TemplateArgumentListInfo *TemplateArgsAsWritten, |
1825 | SourceLocation PointOfInstantiation); |
1826 | |
1827 | /// \brief Specify that this record is an instantiation of the |
1828 | /// member function FD. |
1829 | void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD, |
1830 | TemplateSpecializationKind TSK); |
1831 | |
1832 | void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo); |
1833 | |
1834 | protected: |
1835 | FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
1836 | const DeclarationNameInfo &NameInfo, QualType T, |
1837 | TypeSourceInfo *TInfo, StorageClass S, bool isInlineSpecified, |
1838 | bool isConstexprSpecified) |
1839 | : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo, |
1840 | StartLoc), |
1841 | DeclContext(DK), redeclarable_base(C), SClass(S), |
1842 | IsInline(isInlineSpecified), IsInlineSpecified(isInlineSpecified), |
1843 | IsExplicitSpecified(false), IsVirtualAsWritten(false), IsPure(false), |
1844 | HasInheritedPrototype(false), HasWrittenPrototype(true), |
1845 | IsDeleted(false), IsTrivial(false), IsDefaulted(false), |
1846 | IsExplicitlyDefaulted(false), HasImplicitReturnZero(false), |
1847 | IsLateTemplateParsed(false), IsConstexpr(isConstexprSpecified), |
1848 | InstantiationIsPending(false), UsesSEHTry(false), HasSkippedBody(false), |
1849 | WillHaveBody(false), IsCopyDeductionCandidate(false), HasODRHash(false), |
1850 | ODRHash(0), EndRangeLoc(NameInfo.getEndLoc()), |
1851 | DNLoc(NameInfo.getInfo()) {} |
1852 | |
1853 | using redeclarable_base = Redeclarable<FunctionDecl>; |
1854 | |
1855 | FunctionDecl *getNextRedeclarationImpl() override { |
1856 | return getNextRedeclaration(); |
1857 | } |
1858 | |
1859 | FunctionDecl *getPreviousDeclImpl() override { |
1860 | return getPreviousDecl(); |
1861 | } |
1862 | |
1863 | FunctionDecl *getMostRecentDeclImpl() override { |
1864 | return getMostRecentDecl(); |
1865 | } |
1866 | |
1867 | public: |
1868 | friend class ASTDeclReader; |
1869 | friend class ASTDeclWriter; |
1870 | |
1871 | using redecl_range = redeclarable_base::redecl_range; |
1872 | using redecl_iterator = redeclarable_base::redecl_iterator; |
1873 | |
1874 | using redeclarable_base::redecls_begin; |
1875 | using redeclarable_base::redecls_end; |
1876 | using redeclarable_base::redecls; |
1877 | using redeclarable_base::getPreviousDecl; |
1878 | using redeclarable_base::getMostRecentDecl; |
1879 | using redeclarable_base::isFirstDecl; |
1880 | |
1881 | static FunctionDecl *Create(ASTContext &C, DeclContext *DC, |
1882 | SourceLocation StartLoc, SourceLocation NLoc, |
1883 | DeclarationName N, QualType T, |
1884 | TypeSourceInfo *TInfo, |
1885 | StorageClass SC, |
1886 | bool isInlineSpecified = false, |
1887 | bool hasWrittenPrototype = true, |
1888 | bool isConstexprSpecified = false) { |
1889 | DeclarationNameInfo NameInfo(N, NLoc); |
1890 | return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo, |
1891 | SC, |
1892 | isInlineSpecified, hasWrittenPrototype, |
1893 | isConstexprSpecified); |
1894 | } |
1895 | |
1896 | static FunctionDecl *Create(ASTContext &C, DeclContext *DC, |
1897 | SourceLocation StartLoc, |
1898 | const DeclarationNameInfo &NameInfo, |
1899 | QualType T, TypeSourceInfo *TInfo, |
1900 | StorageClass SC, |
1901 | bool isInlineSpecified, |
1902 | bool hasWrittenPrototype, |
1903 | bool isConstexprSpecified = false); |
1904 | |
1905 | static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
1906 | |
1907 | DeclarationNameInfo getNameInfo() const { |
1908 | return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc); |
1909 | } |
1910 | |
1911 | void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, |
1912 | bool Qualified) const override; |
1913 | |
1914 | void setRangeEnd(SourceLocation E) { EndRangeLoc = E; } |
1915 | |
1916 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
1917 | |
1918 | /// \brief Returns true if the function has a body (definition). The |
1919 | /// function body might be in any of the (re-)declarations of this |
1920 | /// function. The variant that accepts a FunctionDecl pointer will |
1921 | /// set that function declaration to the actual declaration |
1922 | /// containing the body (if there is one). |
1923 | bool hasBody(const FunctionDecl *&Definition) const; |
1924 | |
1925 | bool hasBody() const override { |
1926 | const FunctionDecl* Definition; |
1927 | return hasBody(Definition); |
1928 | } |
1929 | |
1930 | /// Returns whether the function has a trivial body that does not require any |
1931 | /// specific codegen. |
1932 | bool hasTrivialBody() const; |
1933 | |
1934 | /// Returns true if the function is defined at all, including a deleted |
1935 | /// definition. Except for the behavior when the function is deleted, behaves |
1936 | /// like hasBody. |
1937 | bool isDefined(const FunctionDecl *&Definition) const; |
1938 | |
1939 | virtual bool isDefined() const { |
1940 | const FunctionDecl* Definition; |
1941 | return isDefined(Definition); |
1942 | } |
1943 | |
1944 | /// \brief Get the definition for this declaration. |
1945 | FunctionDecl *getDefinition() { |
1946 | const FunctionDecl *Definition; |
1947 | if (isDefined(Definition)) |
1948 | return const_cast<FunctionDecl *>(Definition); |
1949 | return nullptr; |
1950 | } |
1951 | const FunctionDecl *getDefinition() const { |
1952 | return const_cast<FunctionDecl *>(this)->getDefinition(); |
1953 | } |
1954 | |
1955 | /// Retrieve the body (definition) of the function. The function body might be |
1956 | /// in any of the (re-)declarations of this function. The variant that accepts |
1957 | /// a FunctionDecl pointer will set that function declaration to the actual |
1958 | /// declaration containing the body (if there is one). |
1959 | /// NOTE: For checking if there is a body, use hasBody() instead, to avoid |
1960 | /// unnecessary AST de-serialization of the body. |
1961 | Stmt *getBody(const FunctionDecl *&Definition) const; |
1962 | |
1963 | Stmt *getBody() const override { |
1964 | const FunctionDecl* Definition; |
1965 | return getBody(Definition); |
1966 | } |
1967 | |
1968 | /// Returns whether this specific declaration of the function is also a |
1969 | /// definition that does not contain uninstantiated body. |
1970 | /// |
1971 | /// This does not determine whether the function has been defined (e.g., in a |
1972 | /// previous definition); for that information, use isDefined. |
1973 | bool isThisDeclarationADefinition() const { |
1974 | return IsDeleted || IsDefaulted || Body || HasSkippedBody || |
1975 | IsLateTemplateParsed || WillHaveBody || hasDefiningAttr(); |
1976 | } |
1977 | |
1978 | /// Returns whether this specific declaration of the function has a body - |
1979 | /// that is, if it is a non-deleted definition. |
1980 | bool doesThisDeclarationHaveABody() const { |
1981 | return Body || IsLateTemplateParsed; |
1982 | } |
1983 | |
1984 | void setBody(Stmt *B); |
1985 | void setLazyBody(uint64_t Offset) { Body = Offset; } |
1986 | |
1987 | /// Whether this function is variadic. |
1988 | bool isVariadic() const; |
1989 | |
1990 | /// Whether this function is marked as virtual explicitly. |
1991 | bool isVirtualAsWritten() const { return IsVirtualAsWritten; } |
1992 | void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; } |
1993 | |
1994 | /// Whether this virtual function is pure, i.e. makes the containing class |
1995 | /// abstract. |
1996 | bool isPure() const { return IsPure; } |
1997 | void setPure(bool P = true); |
1998 | |
1999 | /// Whether this templated function will be late parsed. |
2000 | bool isLateTemplateParsed() const { return IsLateTemplateParsed; } |
2001 | void setLateTemplateParsed(bool ILT = true) { IsLateTemplateParsed = ILT; } |
2002 | |
2003 | /// Whether this function is "trivial" in some specialized C++ senses. |
2004 | /// Can only be true for default constructors, copy constructors, |
2005 | /// copy assignment operators, and destructors. Not meaningful until |
2006 | /// the class has been fully built by Sema. |
2007 | bool isTrivial() const { return IsTrivial; } |
2008 | void setTrivial(bool IT) { IsTrivial = IT; } |
2009 | |
2010 | /// Whether this function is defaulted per C++0x. Only valid for |
2011 | /// special member functions. |
2012 | bool isDefaulted() const { return IsDefaulted; } |
2013 | void setDefaulted(bool D = true) { IsDefaulted = D; } |
2014 | |
2015 | /// Whether this function is explicitly defaulted per C++0x. Only valid |
2016 | /// for special member functions. |
2017 | bool isExplicitlyDefaulted() const { return IsExplicitlyDefaulted; } |
2018 | void setExplicitlyDefaulted(bool ED = true) { IsExplicitlyDefaulted = ED; } |
2019 | |
2020 | /// Whether falling off this function implicitly returns null/zero. |
2021 | /// If a more specific implicit return value is required, front-ends |
2022 | /// should synthesize the appropriate return statements. |
2023 | bool hasImplicitReturnZero() const { return HasImplicitReturnZero; } |
2024 | void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; } |
2025 | |
2026 | /// \brief Whether this function has a prototype, either because one |
2027 | /// was explicitly written or because it was "inherited" by merging |
2028 | /// a declaration without a prototype with a declaration that has a |
2029 | /// prototype. |
2030 | bool hasPrototype() const { |
2031 | return HasWrittenPrototype || HasInheritedPrototype; |
2032 | } |
2033 | |
2034 | bool hasWrittenPrototype() const { return HasWrittenPrototype; } |
2035 | |
2036 | /// \brief Whether this function inherited its prototype from a |
2037 | /// previous declaration. |
2038 | bool hasInheritedPrototype() const { return HasInheritedPrototype; } |
2039 | void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; } |
2040 | |
2041 | /// Whether this is a (C++11) constexpr function or constexpr constructor. |
2042 | bool isConstexpr() const { return IsConstexpr; } |
2043 | void setConstexpr(bool IC) { IsConstexpr = IC; } |
2044 | |
2045 | /// \brief Whether the instantiation of this function is pending. |
2046 | /// This bit is set when the decision to instantiate this function is made |
2047 | /// and unset if and when the function body is created. That leaves out |
2048 | /// cases where instantiation did not happen because the template definition |
2049 | /// was not seen in this TU. This bit remains set in those cases, under the |
2050 | /// assumption that the instantiation will happen in some other TU. |
2051 | bool instantiationIsPending() const { return InstantiationIsPending; } |
2052 | void setInstantiationIsPending(bool IC) { InstantiationIsPending = IC; } |
2053 | |
2054 | /// \brief Indicates the function uses __try. |
2055 | bool usesSEHTry() const { return UsesSEHTry; } |
2056 | void setUsesSEHTry(bool UST) { UsesSEHTry = UST; } |
2057 | |
2058 | /// \brief Whether this function has been deleted. |
2059 | /// |
2060 | /// A function that is "deleted" (via the C++0x "= delete" syntax) |
2061 | /// acts like a normal function, except that it cannot actually be |
2062 | /// called or have its address taken. Deleted functions are |
2063 | /// typically used in C++ overload resolution to attract arguments |
2064 | /// whose type or lvalue/rvalue-ness would permit the use of a |
2065 | /// different overload that would behave incorrectly. For example, |
2066 | /// one might use deleted functions to ban implicit conversion from |
2067 | /// a floating-point number to an Integer type: |
2068 | /// |
2069 | /// @code |
2070 | /// struct Integer { |
2071 | /// Integer(long); // construct from a long |
2072 | /// Integer(double) = delete; // no construction from float or double |
2073 | /// Integer(long double) = delete; // no construction from long double |
2074 | /// }; |
2075 | /// @endcode |
2076 | // If a function is deleted, its first declaration must be. |
2077 | bool isDeleted() const { return getCanonicalDecl()->IsDeleted; } |
2078 | bool isDeletedAsWritten() const { return IsDeleted && !IsDefaulted; } |
2079 | void setDeletedAsWritten(bool D = true) { IsDeleted = D; } |
2080 | |
2081 | /// \brief Determines whether this function is "main", which is the |
2082 | /// entry point into an executable program. |
2083 | bool isMain() const; |
2084 | |
2085 | /// \brief Determines whether this function is a MSVCRT user defined entry |
2086 | /// point. |
2087 | bool isMSVCRTEntryPoint() const; |
2088 | |
2089 | /// \brief Determines whether this operator new or delete is one |
2090 | /// of the reserved global placement operators: |
2091 | /// void *operator new(size_t, void *); |
2092 | /// void *operator new[](size_t, void *); |
2093 | /// void operator delete(void *, void *); |
2094 | /// void operator delete[](void *, void *); |
2095 | /// These functions have special behavior under [new.delete.placement]: |
2096 | /// These functions are reserved, a C++ program may not define |
2097 | /// functions that displace the versions in the Standard C++ library. |
2098 | /// The provisions of [basic.stc.dynamic] do not apply to these |
2099 | /// reserved placement forms of operator new and operator delete. |
2100 | /// |
2101 | /// This function must be an allocation or deallocation function. |
2102 | bool isReservedGlobalPlacementOperator() const; |
2103 | |
2104 | /// \brief Determines whether this function is one of the replaceable |
2105 | /// global allocation functions: |
2106 | /// void *operator new(size_t); |
2107 | /// void *operator new(size_t, const std::nothrow_t &) noexcept; |
2108 | /// void *operator new[](size_t); |
2109 | /// void *operator new[](size_t, const std::nothrow_t &) noexcept; |
2110 | /// void operator delete(void *) noexcept; |
2111 | /// void operator delete(void *, std::size_t) noexcept; [C++1y] |
2112 | /// void operator delete(void *, const std::nothrow_t &) noexcept; |
2113 | /// void operator delete[](void *) noexcept; |
2114 | /// void operator delete[](void *, std::size_t) noexcept; [C++1y] |
2115 | /// void operator delete[](void *, const std::nothrow_t &) noexcept; |
2116 | /// These functions have special behavior under C++1y [expr.new]: |
2117 | /// An implementation is allowed to omit a call to a replaceable global |
2118 | /// allocation function. [...] |
2119 | /// |
2120 | /// If this function is an aligned allocation/deallocation function, return |
2121 | /// true through IsAligned. |
2122 | bool isReplaceableGlobalAllocationFunction(bool *IsAligned = nullptr) const; |
2123 | |
2124 | /// \brief Determine whether this is a destroying operator delete. |
2125 | bool isDestroyingOperatorDelete() const; |
2126 | |
2127 | /// Compute the language linkage. |
2128 | LanguageLinkage getLanguageLinkage() const; |
2129 | |
2130 | /// \brief Determines whether this function is a function with |
2131 | /// external, C linkage. |
2132 | bool isExternC() const; |
2133 | |
2134 | /// \brief Determines whether this function's context is, or is nested within, |
2135 | /// a C++ extern "C" linkage spec. |
2136 | bool isInExternCContext() const; |
2137 | |
2138 | /// \brief Determines whether this function's context is, or is nested within, |
2139 | /// a C++ extern "C++" linkage spec. |
2140 | bool isInExternCXXContext() const; |
2141 | |
2142 | /// \brief Determines whether this is a global function. |
2143 | bool isGlobal() const; |
2144 | |
2145 | /// \brief Determines whether this function is known to be 'noreturn', through |
2146 | /// an attribute on its declaration or its type. |
2147 | bool isNoReturn() const; |
2148 | |
2149 | /// \brief True if the function was a definition but its body was skipped. |
2150 | bool hasSkippedBody() const { return HasSkippedBody; } |
2151 | void setHasSkippedBody(bool Skipped = true) { HasSkippedBody = Skipped; } |
2152 | |
2153 | /// True if this function will eventually have a body, once it's fully parsed. |
2154 | bool willHaveBody() const { return WillHaveBody; } |
2155 | void setWillHaveBody(bool V = true) { WillHaveBody = V; } |
2156 | |
2157 | void setPreviousDeclaration(FunctionDecl * PrevDecl); |
2158 | |
2159 | FunctionDecl *getCanonicalDecl() override; |
2160 | const FunctionDecl *getCanonicalDecl() const { |
2161 | return const_cast<FunctionDecl*>(this)->getCanonicalDecl(); |
2162 | } |
2163 | |
2164 | unsigned getBuiltinID() const; |
2165 | |
2166 | // ArrayRef interface to parameters. |
2167 | ArrayRef<ParmVarDecl *> parameters() const { |
2168 | return {ParamInfo, getNumParams()}; |
2169 | } |
2170 | MutableArrayRef<ParmVarDecl *> parameters() { |
2171 | return {ParamInfo, getNumParams()}; |
2172 | } |
2173 | |
2174 | // Iterator access to formal parameters. |
2175 | using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator; |
2176 | using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator; |
2177 | |
2178 | bool param_empty() const { return parameters().empty(); } |
2179 | param_iterator param_begin() { return parameters().begin(); } |
2180 | param_iterator param_end() { return parameters().end(); } |
2181 | param_const_iterator param_begin() const { return parameters().begin(); } |
2182 | param_const_iterator param_end() const { return parameters().end(); } |
2183 | size_t param_size() const { return parameters().size(); } |
2184 | |
2185 | /// Return the number of parameters this function must have based on its |
2186 | /// FunctionType. This is the length of the ParamInfo array after it has been |
2187 | /// created. |
2188 | unsigned getNumParams() const; |
2189 | |
2190 | const ParmVarDecl *getParamDecl(unsigned i) const { |
2191 | assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #" ) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 2191, __extension__ __PRETTY_FUNCTION__)); |
2192 | return ParamInfo[i]; |
2193 | } |
2194 | ParmVarDecl *getParamDecl(unsigned i) { |
2195 | assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #" ) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 2195, __extension__ __PRETTY_FUNCTION__)); |
2196 | return ParamInfo[i]; |
2197 | } |
2198 | void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) { |
2199 | setParams(getASTContext(), NewParamInfo); |
2200 | } |
2201 | |
2202 | /// Returns the minimum number of arguments needed to call this function. This |
2203 | /// may be fewer than the number of function parameters, if some of the |
2204 | /// parameters have default arguments (in C++). |
2205 | unsigned getMinRequiredArguments() const; |
2206 | |
2207 | QualType getReturnType() const { |
2208 | assert(getType()->getAs<FunctionType>() && "Expected a FunctionType!")(static_cast <bool> (getType()->getAs<FunctionType >() && "Expected a FunctionType!") ? void (0) : __assert_fail ("getType()->getAs<FunctionType>() && \"Expected a FunctionType!\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 2208, __extension__ __PRETTY_FUNCTION__)); |
2209 | return getType()->getAs<FunctionType>()->getReturnType(); |
2210 | } |
2211 | |
2212 | /// \brief Attempt to compute an informative source range covering the |
2213 | /// function return type. This may omit qualifiers and other information with |
2214 | /// limited representation in the AST. |
2215 | SourceRange getReturnTypeSourceRange() const; |
2216 | |
2217 | /// \brief Attempt to compute an informative source range covering the |
2218 | /// function exception specification, if any. |
2219 | SourceRange getExceptionSpecSourceRange() const; |
2220 | |
2221 | /// \brief Determine the type of an expression that calls this function. |
2222 | QualType getCallResultType() const { |
2223 | assert(getType()->getAs<FunctionType>() && "Expected a FunctionType!")(static_cast <bool> (getType()->getAs<FunctionType >() && "Expected a FunctionType!") ? void (0) : __assert_fail ("getType()->getAs<FunctionType>() && \"Expected a FunctionType!\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 2223, __extension__ __PRETTY_FUNCTION__)); |
2224 | return getType()->getAs<FunctionType>()->getCallResultType(getASTContext()); |
2225 | } |
2226 | |
2227 | /// \brief Returns the WarnUnusedResultAttr that is either declared on this |
2228 | /// function, or its return type declaration. |
2229 | const Attr *getUnusedResultAttr() const; |
2230 | |
2231 | /// \brief Returns true if this function or its return type has the |
2232 | /// warn_unused_result attribute. |
2233 | bool hasUnusedResultAttr() const { return getUnusedResultAttr() != nullptr; } |
2234 | |
2235 | /// \brief Returns the storage class as written in the source. For the |
2236 | /// computed linkage of symbol, see getLinkage. |
2237 | StorageClass getStorageClass() const { return StorageClass(SClass); } |
2238 | |
2239 | /// \brief Determine whether the "inline" keyword was specified for this |
2240 | /// function. |
2241 | bool isInlineSpecified() const { return IsInlineSpecified; } |
2242 | |
2243 | /// Set whether the "inline" keyword was specified for this function. |
2244 | void setInlineSpecified(bool I) { |
2245 | IsInlineSpecified = I; |
2246 | IsInline = I; |
2247 | } |
2248 | |
2249 | /// Flag that this function is implicitly inline. |
2250 | void setImplicitlyInline() { |
2251 | IsInline = true; |
2252 | } |
2253 | |
2254 | /// \brief Determine whether this function should be inlined, because it is |
2255 | /// either marked "inline" or "constexpr" or is a member function of a class |
2256 | /// that was defined in the class body. |
2257 | bool isInlined() const { return IsInline; } |
2258 | |
2259 | bool isInlineDefinitionExternallyVisible() const; |
2260 | |
2261 | bool isMSExternInline() const; |
2262 | |
2263 | bool doesDeclarationForceExternallyVisibleDefinition() const; |
2264 | |
2265 | /// isOverloadedOperator - Whether this function declaration |
2266 | /// represents an C++ overloaded operator, e.g., "operator+". |
2267 | bool isOverloadedOperator() const { |
2268 | return getOverloadedOperator() != OO_None; |
2269 | } |
2270 | |
2271 | OverloadedOperatorKind getOverloadedOperator() const; |
2272 | |
2273 | const IdentifierInfo *getLiteralIdentifier() const; |
2274 | |
2275 | /// \brief If this function is an instantiation of a member function |
2276 | /// of a class template specialization, retrieves the function from |
2277 | /// which it was instantiated. |
2278 | /// |
2279 | /// This routine will return non-NULL for (non-templated) member |
2280 | /// functions of class templates and for instantiations of function |
2281 | /// templates. For example, given: |
2282 | /// |
2283 | /// \code |
2284 | /// template<typename T> |
2285 | /// struct X { |
2286 | /// void f(T); |
2287 | /// }; |
2288 | /// \endcode |
2289 | /// |
2290 | /// The declaration for X<int>::f is a (non-templated) FunctionDecl |
2291 | /// whose parent is the class template specialization X<int>. For |
2292 | /// this declaration, getInstantiatedFromFunction() will return |
2293 | /// the FunctionDecl X<T>::A. When a complete definition of |
2294 | /// X<int>::A is required, it will be instantiated from the |
2295 | /// declaration returned by getInstantiatedFromMemberFunction(). |
2296 | FunctionDecl *getInstantiatedFromMemberFunction() const; |
2297 | |
2298 | /// \brief What kind of templated function this is. |
2299 | TemplatedKind getTemplatedKind() const; |
2300 | |
2301 | /// \brief If this function is an instantiation of a member function of a |
2302 | /// class template specialization, retrieves the member specialization |
2303 | /// information. |
2304 | MemberSpecializationInfo *getMemberSpecializationInfo() const; |
2305 | |
2306 | /// \brief Specify that this record is an instantiation of the |
2307 | /// member function FD. |
2308 | void setInstantiationOfMemberFunction(FunctionDecl *FD, |
2309 | TemplateSpecializationKind TSK) { |
2310 | setInstantiationOfMemberFunction(getASTContext(), FD, TSK); |
2311 | } |
2312 | |
2313 | /// \brief Retrieves the function template that is described by this |
2314 | /// function declaration. |
2315 | /// |
2316 | /// Every function template is represented as a FunctionTemplateDecl |
2317 | /// and a FunctionDecl (or something derived from FunctionDecl). The |
2318 | /// former contains template properties (such as the template |
2319 | /// parameter lists) while the latter contains the actual |
2320 | /// description of the template's |
2321 | /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the |
2322 | /// FunctionDecl that describes the function template, |
2323 | /// getDescribedFunctionTemplate() retrieves the |
2324 | /// FunctionTemplateDecl from a FunctionDecl. |
2325 | FunctionTemplateDecl *getDescribedFunctionTemplate() const; |
2326 | |
2327 | void setDescribedFunctionTemplate(FunctionTemplateDecl *Template); |
2328 | |
2329 | /// \brief Determine whether this function is a function template |
2330 | /// specialization. |
2331 | bool isFunctionTemplateSpecialization() const { |
2332 | return getPrimaryTemplate() != nullptr; |
2333 | } |
2334 | |
2335 | /// \brief Retrieve the class scope template pattern that this function |
2336 | /// template specialization is instantiated from. |
2337 | FunctionDecl *getClassScopeSpecializationPattern() const; |
2338 | |
2339 | /// \brief If this function is actually a function template specialization, |
2340 | /// retrieve information about this function template specialization. |
2341 | /// Otherwise, returns NULL. |
2342 | FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const; |
2343 | |
2344 | /// \brief Determines whether this function is a function template |
2345 | /// specialization or a member of a class template specialization that can |
2346 | /// be implicitly instantiated. |
2347 | bool isImplicitlyInstantiable() const; |
2348 | |
2349 | /// \brief Determines if the given function was instantiated from a |
2350 | /// function template. |
2351 | bool isTemplateInstantiation() const; |
2352 | |
2353 | /// \brief Retrieve the function declaration from which this function could |
2354 | /// be instantiated, if it is an instantiation (rather than a non-template |
2355 | /// or a specialization, for example). |
2356 | FunctionDecl *getTemplateInstantiationPattern() const; |
2357 | |
2358 | /// \brief Retrieve the primary template that this function template |
2359 | /// specialization either specializes or was instantiated from. |
2360 | /// |
2361 | /// If this function declaration is not a function template specialization, |
2362 | /// returns NULL. |
2363 | FunctionTemplateDecl *getPrimaryTemplate() const; |
2364 | |
2365 | /// \brief Retrieve the template arguments used to produce this function |
2366 | /// template specialization from the primary template. |
2367 | /// |
2368 | /// If this function declaration is not a function template specialization, |
2369 | /// returns NULL. |
2370 | const TemplateArgumentList *getTemplateSpecializationArgs() const; |
2371 | |
2372 | /// \brief Retrieve the template argument list as written in the sources, |
2373 | /// if any. |
2374 | /// |
2375 | /// If this function declaration is not a function template specialization |
2376 | /// or if it had no explicit template argument list, returns NULL. |
2377 | /// Note that it an explicit template argument list may be written empty, |
2378 | /// e.g., template<> void foo<>(char* s); |
2379 | const ASTTemplateArgumentListInfo* |
2380 | getTemplateSpecializationArgsAsWritten() const; |
2381 | |
2382 | /// \brief Specify that this function declaration is actually a function |
2383 | /// template specialization. |
2384 | /// |
2385 | /// \param Template the function template that this function template |
2386 | /// specialization specializes. |
2387 | /// |
2388 | /// \param TemplateArgs the template arguments that produced this |
2389 | /// function template specialization from the template. |
2390 | /// |
2391 | /// \param InsertPos If non-NULL, the position in the function template |
2392 | /// specialization set where the function template specialization data will |
2393 | /// be inserted. |
2394 | /// |
2395 | /// \param TSK the kind of template specialization this is. |
2396 | /// |
2397 | /// \param TemplateArgsAsWritten location info of template arguments. |
2398 | /// |
2399 | /// \param PointOfInstantiation point at which the function template |
2400 | /// specialization was first instantiated. |
2401 | void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template, |
2402 | const TemplateArgumentList *TemplateArgs, |
2403 | void *InsertPos, |
2404 | TemplateSpecializationKind TSK = TSK_ImplicitInstantiation, |
2405 | const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr, |
2406 | SourceLocation PointOfInstantiation = SourceLocation()) { |
2407 | setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs, |
2408 | InsertPos, TSK, TemplateArgsAsWritten, |
2409 | PointOfInstantiation); |
2410 | } |
2411 | |
2412 | /// \brief Specifies that this function declaration is actually a |
2413 | /// dependent function template specialization. |
2414 | void setDependentTemplateSpecialization(ASTContext &Context, |
2415 | const UnresolvedSetImpl &Templates, |
2416 | const TemplateArgumentListInfo &TemplateArgs); |
2417 | |
2418 | DependentFunctionTemplateSpecializationInfo * |
2419 | getDependentSpecializationInfo() const; |
2420 | |
2421 | /// \brief Determine what kind of template instantiation this function |
2422 | /// represents. |
2423 | TemplateSpecializationKind getTemplateSpecializationKind() const; |
2424 | |
2425 | /// \brief Determine what kind of template instantiation this function |
2426 | /// represents. |
2427 | void setTemplateSpecializationKind(TemplateSpecializationKind TSK, |
2428 | SourceLocation PointOfInstantiation = SourceLocation()); |
2429 | |
2430 | /// \brief Retrieve the (first) point of instantiation of a function template |
2431 | /// specialization or a member of a class template specialization. |
2432 | /// |
2433 | /// \returns the first point of instantiation, if this function was |
2434 | /// instantiated from a template; otherwise, returns an invalid source |
2435 | /// location. |
2436 | SourceLocation getPointOfInstantiation() const; |
2437 | |
2438 | /// \brief Determine whether this is or was instantiated from an out-of-line |
2439 | /// definition of a member function. |
2440 | bool isOutOfLine() const override; |
2441 | |
2442 | /// \brief Identify a memory copying or setting function. |
2443 | /// If the given function is a memory copy or setting function, returns |
2444 | /// the corresponding Builtin ID. If the function is not a memory function, |
2445 | /// returns 0. |
2446 | unsigned getMemoryFunctionKind() const; |
2447 | |
2448 | /// \brief Returns ODRHash of the function. This value is calculated and |
2449 | /// stored on first call, then the stored value returned on the other calls. |
2450 | unsigned getODRHash(); |
2451 | |
2452 | // Implement isa/cast/dyncast/etc. |
2453 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2454 | static bool classofKind(Kind K) { |
2455 | return K >= firstFunction && K <= lastFunction; |
2456 | } |
2457 | static DeclContext *castToDeclContext(const FunctionDecl *D) { |
2458 | return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D)); |
2459 | } |
2460 | static FunctionDecl *castFromDeclContext(const DeclContext *DC) { |
2461 | return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC)); |
2462 | } |
2463 | }; |
2464 | |
2465 | /// FieldDecl - An instance of this class is created by Sema::ActOnField to |
2466 | /// represent a member of a struct/union/class. |
2467 | class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> { |
2468 | unsigned BitField : 1; |
2469 | unsigned Mutable : 1; |
2470 | mutable unsigned CachedFieldIndex : 30; |
2471 | |
2472 | /// The kinds of value we can store in InitializerOrBitWidth. |
2473 | /// |
2474 | /// Note that this is compatible with InClassInitStyle except for |
2475 | /// ISK_CapturedVLAType. |
2476 | enum InitStorageKind { |
2477 | /// If the pointer is null, there's nothing special. Otherwise, |
2478 | /// this is a bitfield and the pointer is the Expr* storing the |
2479 | /// bit-width. |
2480 | ISK_NoInit = (unsigned) ICIS_NoInit, |
2481 | |
2482 | /// The pointer is an (optional due to delayed parsing) Expr* |
2483 | /// holding the copy-initializer. |
2484 | ISK_InClassCopyInit = (unsigned) ICIS_CopyInit, |
2485 | |
2486 | /// The pointer is an (optional due to delayed parsing) Expr* |
2487 | /// holding the list-initializer. |
2488 | ISK_InClassListInit = (unsigned) ICIS_ListInit, |
2489 | |
2490 | /// The pointer is a VariableArrayType* that's been captured; |
2491 | /// the enclosing context is a lambda or captured statement. |
2492 | ISK_CapturedVLAType, |
2493 | }; |
2494 | |
2495 | /// If this is a bitfield with a default member initializer, this |
2496 | /// structure is used to represent the two expressions. |
2497 | struct InitAndBitWidth { |
2498 | Expr *Init; |
2499 | Expr *BitWidth; |
2500 | }; |
2501 | |
2502 | /// \brief Storage for either the bit-width, the in-class initializer, or |
2503 | /// both (via InitAndBitWidth), or the captured variable length array bound. |
2504 | /// |
2505 | /// If the storage kind is ISK_InClassCopyInit or |
2506 | /// ISK_InClassListInit, but the initializer is null, then this |
2507 | /// field has an in-class initializer that has not yet been parsed |
2508 | /// and attached. |
2509 | // FIXME: Tail-allocate this to reduce the size of FieldDecl in the |
2510 | // overwhelmingly common case that we have none of these things. |
2511 | llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage; |
2512 | |
2513 | protected: |
2514 | FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc, |
2515 | SourceLocation IdLoc, IdentifierInfo *Id, |
2516 | QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, |
2517 | InClassInitStyle InitStyle) |
2518 | : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), |
2519 | BitField(false), Mutable(Mutable), CachedFieldIndex(0), |
2520 | InitStorage(nullptr, (InitStorageKind) InitStyle) { |
2521 | if (BW) |
2522 | setBitWidth(BW); |
2523 | } |
2524 | |
2525 | public: |
2526 | friend class ASTDeclReader; |
2527 | friend class ASTDeclWriter; |
2528 | |
2529 | static FieldDecl *Create(const ASTContext &C, DeclContext *DC, |
2530 | SourceLocation StartLoc, SourceLocation IdLoc, |
2531 | IdentifierInfo *Id, QualType T, |
2532 | TypeSourceInfo *TInfo, Expr *BW, bool Mutable, |
2533 | InClassInitStyle InitStyle); |
2534 | |
2535 | static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
2536 | |
2537 | /// getFieldIndex - Returns the index of this field within its record, |
2538 | /// as appropriate for passing to ASTRecordLayout::getFieldOffset. |
2539 | unsigned getFieldIndex() const; |
2540 | |
2541 | /// isMutable - Determines whether this field is mutable (C++ only). |
2542 | bool isMutable() const { return Mutable; } |
2543 | |
2544 | /// \brief Determines whether this field is a bitfield. |
2545 | bool isBitField() const { return BitField; } |
2546 | |
2547 | /// @brief Determines whether this is an unnamed bitfield. |
2548 | bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); } |
2549 | |
2550 | /// isAnonymousStructOrUnion - Determines whether this field is a |
2551 | /// representative for an anonymous struct or union. Such fields are |
2552 | /// unnamed and are implicitly generated by the implementation to |
2553 | /// store the data for the anonymous union or struct. |
2554 | bool isAnonymousStructOrUnion() const; |
2555 | |
2556 | Expr *getBitWidth() const { |
2557 | if (!BitField) |
2558 | return nullptr; |
2559 | void *Ptr = InitStorage.getPointer(); |
2560 | if (getInClassInitStyle()) |
2561 | return static_cast<InitAndBitWidth*>(Ptr)->BitWidth; |
2562 | return static_cast<Expr*>(Ptr); |
2563 | } |
2564 | |
2565 | unsigned getBitWidthValue(const ASTContext &Ctx) const; |
2566 | |
2567 | /// setBitWidth - Set the bit-field width for this member. |
2568 | // Note: used by some clients (i.e., do not remove it). |
2569 | void setBitWidth(Expr *Width) { |
2570 | assert(!hasCapturedVLAType() && !BitField &&(static_cast <bool> (!hasCapturedVLAType() && ! BitField && "bit width or captured type already set") ? void (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 2571, __extension__ __PRETTY_FUNCTION__)) |
2571 | "bit width or captured type already set")(static_cast <bool> (!hasCapturedVLAType() && ! BitField && "bit width or captured type already set") ? void (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 2571, __extension__ __PRETTY_FUNCTION__)); |
2572 | assert(Width && "no bit width specified")(static_cast <bool> (Width && "no bit width specified" ) ? void (0) : __assert_fail ("Width && \"no bit width specified\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 2572, __extension__ __PRETTY_FUNCTION__)); |
2573 | InitStorage.setPointer( |
2574 | InitStorage.getInt() |
2575 | ? new (getASTContext()) |
2576 | InitAndBitWidth{getInClassInitializer(), Width} |
2577 | : static_cast<void*>(Width)); |
2578 | BitField = true; |
2579 | } |
2580 | |
2581 | /// removeBitWidth - Remove the bit-field width from this member. |
2582 | // Note: used by some clients (i.e., do not remove it). |
2583 | void removeBitWidth() { |
2584 | assert(isBitField() && "no bitfield width to remove")(static_cast <bool> (isBitField() && "no bitfield width to remove" ) ? void (0) : __assert_fail ("isBitField() && \"no bitfield width to remove\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 2584, __extension__ __PRETTY_FUNCTION__)); |
2585 | InitStorage.setPointer(getInClassInitializer()); |
2586 | BitField = false; |
2587 | } |
2588 | |
2589 | /// Get the kind of (C++11) default member initializer that this field has. |
2590 | InClassInitStyle getInClassInitStyle() const { |
2591 | InitStorageKind storageKind = InitStorage.getInt(); |
2592 | return (storageKind == ISK_CapturedVLAType |
2593 | ? ICIS_NoInit : (InClassInitStyle) storageKind); |
2594 | } |
2595 | |
2596 | /// Determine whether this member has a C++11 default member initializer. |
2597 | bool hasInClassInitializer() const { |
2598 | return getInClassInitStyle() != ICIS_NoInit; |
2599 | } |
2600 | |
2601 | /// Get the C++11 default member initializer for this member, or null if one |
2602 | /// has not been set. If a valid declaration has a default member initializer, |
2603 | /// but this returns null, then we have not parsed and attached it yet. |
2604 | Expr *getInClassInitializer() const { |
2605 | if (!hasInClassInitializer()) |
2606 | return nullptr; |
2607 | void *Ptr = InitStorage.getPointer(); |
2608 | if (BitField) |
2609 | return static_cast<InitAndBitWidth*>(Ptr)->Init; |
2610 | return static_cast<Expr*>(Ptr); |
2611 | } |
2612 | |
2613 | /// setInClassInitializer - Set the C++11 in-class initializer for this |
2614 | /// member. |
2615 | void setInClassInitializer(Expr *Init) { |
2616 | assert(hasInClassInitializer() && !getInClassInitializer())(static_cast <bool> (hasInClassInitializer() && !getInClassInitializer()) ? void (0) : __assert_fail ("hasInClassInitializer() && !getInClassInitializer()" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 2616, __extension__ __PRETTY_FUNCTION__)); |
2617 | if (BitField) |
2618 | static_cast<InitAndBitWidth*>(InitStorage.getPointer())->Init = Init; |
2619 | else |
2620 | InitStorage.setPointer(Init); |
2621 | } |
2622 | |
2623 | /// removeInClassInitializer - Remove the C++11 in-class initializer from this |
2624 | /// member. |
2625 | void removeInClassInitializer() { |
2626 | assert(hasInClassInitializer() && "no initializer to remove")(static_cast <bool> (hasInClassInitializer() && "no initializer to remove") ? void (0) : __assert_fail ("hasInClassInitializer() && \"no initializer to remove\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 2626, __extension__ __PRETTY_FUNCTION__)); |
2627 | InitStorage.setPointerAndInt(getBitWidth(), ISK_NoInit); |
2628 | } |
2629 | |
2630 | /// \brief Determine whether this member captures the variable length array |
2631 | /// type. |
2632 | bool hasCapturedVLAType() const { |
2633 | return InitStorage.getInt() == ISK_CapturedVLAType; |
2634 | } |
2635 | |
2636 | /// \brief Get the captured variable length array type. |
2637 | const VariableArrayType *getCapturedVLAType() const { |
2638 | return hasCapturedVLAType() ? static_cast<const VariableArrayType *>( |
2639 | InitStorage.getPointer()) |
2640 | : nullptr; |
2641 | } |
2642 | |
2643 | /// \brief Set the captured variable length array type for this field. |
2644 | void setCapturedVLAType(const VariableArrayType *VLAType); |
2645 | |
2646 | /// getParent - Returns the parent of this field declaration, which |
2647 | /// is the struct in which this field is defined. |
2648 | const RecordDecl *getParent() const { |
2649 | return cast<RecordDecl>(getDeclContext()); |
2650 | } |
2651 | |
2652 | RecordDecl *getParent() { |
2653 | return cast<RecordDecl>(getDeclContext()); |
2654 | } |
2655 | |
2656 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
2657 | |
2658 | /// Retrieves the canonical declaration of this field. |
2659 | FieldDecl *getCanonicalDecl() override { return getFirstDecl(); } |
2660 | const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); } |
2661 | |
2662 | // Implement isa/cast/dyncast/etc. |
2663 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2664 | static bool classofKind(Kind K) { return K >= firstField && K <= lastField; } |
2665 | }; |
2666 | |
2667 | /// EnumConstantDecl - An instance of this object exists for each enum constant |
2668 | /// that is defined. For example, in "enum X {a,b}", each of a/b are |
2669 | /// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a |
2670 | /// TagType for the X EnumDecl. |
2671 | class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> { |
2672 | Stmt *Init; // an integer constant expression |
2673 | llvm::APSInt Val; // The value. |
2674 | |
2675 | protected: |
2676 | EnumConstantDecl(DeclContext *DC, SourceLocation L, |
2677 | IdentifierInfo *Id, QualType T, Expr *E, |
2678 | const llvm::APSInt &V) |
2679 | : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {} |
2680 | |
2681 | public: |
2682 | friend class StmtIteratorBase; |
2683 | |
2684 | static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC, |
2685 | SourceLocation L, IdentifierInfo *Id, |
2686 | QualType T, Expr *E, |
2687 | const llvm::APSInt &V); |
2688 | static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
2689 | |
2690 | const Expr *getInitExpr() const { return (const Expr*) Init; } |
2691 | Expr *getInitExpr() { return (Expr*) Init; } |
2692 | const llvm::APSInt &getInitVal() const { return Val; } |
2693 | |
2694 | void setInitExpr(Expr *E) { Init = (Stmt*) E; } |
2695 | void setInitVal(const llvm::APSInt &V) { Val = V; } |
2696 | |
2697 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
2698 | |
2699 | /// Retrieves the canonical declaration of this enumerator. |
2700 | EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); } |
2701 | const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); } |
2702 | |
2703 | // Implement isa/cast/dyncast/etc. |
2704 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2705 | static bool classofKind(Kind K) { return K == EnumConstant; } |
2706 | }; |
2707 | |
2708 | /// IndirectFieldDecl - An instance of this class is created to represent a |
2709 | /// field injected from an anonymous union/struct into the parent scope. |
2710 | /// IndirectFieldDecl are always implicit. |
2711 | class IndirectFieldDecl : public ValueDecl, |
2712 | public Mergeable<IndirectFieldDecl> { |
2713 | NamedDecl **Chaining; |
2714 | unsigned ChainingSize; |
2715 | |
2716 | IndirectFieldDecl(ASTContext &C, DeclContext *DC, SourceLocation L, |
2717 | DeclarationName N, QualType T, |
2718 | MutableArrayRef<NamedDecl *> CH); |
2719 | |
2720 | void anchor() override; |
2721 | |
2722 | public: |
2723 | friend class ASTDeclReader; |
2724 | |
2725 | static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC, |
2726 | SourceLocation L, IdentifierInfo *Id, |
2727 | QualType T, llvm::MutableArrayRef<NamedDecl *> CH); |
2728 | |
2729 | static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
2730 | |
2731 | using chain_iterator = ArrayRef<NamedDecl *>::const_iterator; |
2732 | |
2733 | ArrayRef<NamedDecl *> chain() const { |
2734 | return llvm::makeArrayRef(Chaining, ChainingSize); |
2735 | } |
2736 | chain_iterator chain_begin() const { return chain().begin(); } |
2737 | chain_iterator chain_end() const { return chain().end(); } |
2738 | |
2739 | unsigned getChainingSize() const { return ChainingSize; } |
2740 | |
2741 | FieldDecl *getAnonField() const { |
2742 | assert(chain().size() >= 2)(static_cast <bool> (chain().size() >= 2) ? void (0) : __assert_fail ("chain().size() >= 2", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 2742, __extension__ __PRETTY_FUNCTION__)); |
2743 | return cast<FieldDecl>(chain().back()); |
2744 | } |
2745 | |
2746 | VarDecl *getVarDecl() const { |
2747 | assert(chain().size() >= 2)(static_cast <bool> (chain().size() >= 2) ? void (0) : __assert_fail ("chain().size() >= 2", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 2747, __extension__ __PRETTY_FUNCTION__)); |
2748 | return dyn_cast<VarDecl>(chain().front()); |
2749 | } |
2750 | |
2751 | IndirectFieldDecl *getCanonicalDecl() override { return getFirstDecl(); } |
2752 | const IndirectFieldDecl *getCanonicalDecl() const { return getFirstDecl(); } |
2753 | |
2754 | // Implement isa/cast/dyncast/etc. |
2755 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2756 | static bool classofKind(Kind K) { return K == IndirectField; } |
2757 | }; |
2758 | |
2759 | /// TypeDecl - Represents a declaration of a type. |
2760 | class TypeDecl : public NamedDecl { |
2761 | friend class ASTContext; |
2762 | |
2763 | /// TypeForDecl - This indicates the Type object that represents |
2764 | /// this TypeDecl. It is a cache maintained by |
2765 | /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and |
2766 | /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl. |
2767 | mutable const Type *TypeForDecl = nullptr; |
2768 | |
2769 | /// LocStart - The start of the source range for this declaration. |
2770 | SourceLocation LocStart; |
2771 | |
2772 | void anchor() override; |
2773 | |
2774 | protected: |
2775 | TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, |
2776 | SourceLocation StartL = SourceLocation()) |
2777 | : NamedDecl(DK, DC, L, Id), LocStart(StartL) {} |
2778 | |
2779 | public: |
2780 | // Low-level accessor. If you just want the type defined by this node, |
2781 | // check out ASTContext::getTypeDeclType or one of |
2782 | // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you |
2783 | // already know the specific kind of node this is. |
2784 | const Type *getTypeForDecl() const { return TypeForDecl; } |
2785 | void setTypeForDecl(const Type *TD) { TypeForDecl = TD; } |
2786 | |
2787 | SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; } |
2788 | void setLocStart(SourceLocation L) { LocStart = L; } |
2789 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
2790 | if (LocStart.isValid()) |
2791 | return SourceRange(LocStart, getLocation()); |
2792 | else |
2793 | return SourceRange(getLocation()); |
2794 | } |
2795 | |
2796 | // Implement isa/cast/dyncast/etc. |
2797 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2798 | static bool classofKind(Kind K) { return K >= firstType && K <= lastType; } |
2799 | }; |
2800 | |
2801 | /// Base class for declarations which introduce a typedef-name. |
2802 | class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> { |
2803 | using ModedTInfo = std::pair<TypeSourceInfo *, QualType>; |
2804 | llvm::PointerUnion<TypeSourceInfo *, ModedTInfo *> MaybeModedTInfo; |
2805 | |
2806 | // FIXME: This can be packed into the bitfields in Decl. |
2807 | /// If 0, we have not computed IsTransparentTag. |
2808 | /// Otherwise, IsTransparentTag is (CacheIsTransparentTag >> 1). |
2809 | mutable unsigned CacheIsTransparentTag : 2; |
2810 | |
2811 | void anchor() override; |
2812 | |
2813 | protected: |
2814 | TypedefNameDecl(Kind DK, ASTContext &C, DeclContext *DC, |
2815 | SourceLocation StartLoc, SourceLocation IdLoc, |
2816 | IdentifierInfo *Id, TypeSourceInfo *TInfo) |
2817 | : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C), |
2818 | MaybeModedTInfo(TInfo), CacheIsTransparentTag(0) {} |
2819 | |
2820 | using redeclarable_base = Redeclarable<TypedefNameDecl>; |
2821 | |
2822 | TypedefNameDecl *getNextRedeclarationImpl() override { |
2823 | return getNextRedeclaration(); |
2824 | } |
2825 | |
2826 | TypedefNameDecl *getPreviousDeclImpl() override { |
2827 | return getPreviousDecl(); |
2828 | } |
2829 | |
2830 | TypedefNameDecl *getMostRecentDeclImpl() override { |
2831 | return getMostRecentDecl(); |
2832 | } |
2833 | |
2834 | public: |
2835 | using redecl_range = redeclarable_base::redecl_range; |
2836 | using redecl_iterator = redeclarable_base::redecl_iterator; |
2837 | |
2838 | using redeclarable_base::redecls_begin; |
2839 | using redeclarable_base::redecls_end; |
2840 | using redeclarable_base::redecls; |
2841 | using redeclarable_base::getPreviousDecl; |
2842 | using redeclarable_base::getMostRecentDecl; |
2843 | using redeclarable_base::isFirstDecl; |
2844 | |
2845 | bool isModed() const { return MaybeModedTInfo.is<ModedTInfo*>(); } |
2846 | |
2847 | TypeSourceInfo *getTypeSourceInfo() const { |
2848 | return isModed() |
2849 | ? MaybeModedTInfo.get<ModedTInfo*>()->first |
2850 | : MaybeModedTInfo.get<TypeSourceInfo*>(); |
2851 | } |
2852 | |
2853 | QualType getUnderlyingType() const { |
2854 | return isModed() |
2855 | ? MaybeModedTInfo.get<ModedTInfo*>()->second |
2856 | : MaybeModedTInfo.get<TypeSourceInfo*>()->getType(); |
2857 | } |
2858 | |
2859 | void setTypeSourceInfo(TypeSourceInfo *newType) { |
2860 | MaybeModedTInfo = newType; |
2861 | } |
2862 | |
2863 | void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) { |
2864 | MaybeModedTInfo = new (getASTContext()) ModedTInfo(unmodedTSI, modedTy); |
2865 | } |
2866 | |
2867 | /// Retrieves the canonical declaration of this typedef-name. |
2868 | TypedefNameDecl *getCanonicalDecl() override { return getFirstDecl(); } |
2869 | const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); } |
2870 | |
2871 | /// Retrieves the tag declaration for which this is the typedef name for |
2872 | /// linkage purposes, if any. |
2873 | /// |
2874 | /// \param AnyRedecl Look for the tag declaration in any redeclaration of |
2875 | /// this typedef declaration. |
2876 | TagDecl *getAnonDeclWithTypedefName(bool AnyRedecl = false) const; |
2877 | |
2878 | /// Determines if this typedef shares a name and spelling location with its |
2879 | /// underlying tag type, as is the case with the NS_ENUM macro. |
2880 | bool isTransparentTag() const { |
2881 | if (CacheIsTransparentTag) |
2882 | return CacheIsTransparentTag & 0x2; |
2883 | return isTransparentTagSlow(); |
2884 | } |
2885 | |
2886 | // Implement isa/cast/dyncast/etc. |
2887 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2888 | static bool classofKind(Kind K) { |
2889 | return K >= firstTypedefName && K <= lastTypedefName; |
2890 | } |
2891 | |
2892 | private: |
2893 | bool isTransparentTagSlow() const; |
2894 | }; |
2895 | |
2896 | /// TypedefDecl - Represents the declaration of a typedef-name via the 'typedef' |
2897 | /// type specifier. |
2898 | class TypedefDecl : public TypedefNameDecl { |
2899 | TypedefDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
2900 | SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo) |
2901 | : TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {} |
2902 | |
2903 | public: |
2904 | static TypedefDecl *Create(ASTContext &C, DeclContext *DC, |
2905 | SourceLocation StartLoc, SourceLocation IdLoc, |
2906 | IdentifierInfo *Id, TypeSourceInfo *TInfo); |
2907 | static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
2908 | |
2909 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
2910 | |
2911 | // Implement isa/cast/dyncast/etc. |
2912 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2913 | static bool classofKind(Kind K) { return K == Typedef; } |
2914 | }; |
2915 | |
2916 | /// TypeAliasDecl - Represents the declaration of a typedef-name via a C++0x |
2917 | /// alias-declaration. |
2918 | class TypeAliasDecl : public TypedefNameDecl { |
2919 | /// The template for which this is the pattern, if any. |
2920 | TypeAliasTemplateDecl *Template; |
2921 | |
2922 | TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
2923 | SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo) |
2924 | : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo), |
2925 | Template(nullptr) {} |
2926 | |
2927 | public: |
2928 | static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC, |
2929 | SourceLocation StartLoc, SourceLocation IdLoc, |
2930 | IdentifierInfo *Id, TypeSourceInfo *TInfo); |
2931 | static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
2932 | |
2933 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
2934 | |
2935 | TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; } |
2936 | void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; } |
2937 | |
2938 | // Implement isa/cast/dyncast/etc. |
2939 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2940 | static bool classofKind(Kind K) { return K == TypeAlias; } |
2941 | }; |
2942 | |
2943 | /// TagDecl - Represents the declaration of a struct/union/class/enum. |
2944 | class TagDecl |
2945 | : public TypeDecl, public DeclContext, public Redeclarable<TagDecl> { |
2946 | public: |
2947 | // This is really ugly. |
2948 | using TagKind = TagTypeKind; |
2949 | |
2950 | private: |
2951 | // FIXME: This can be packed into the bitfields in Decl. |
2952 | /// TagDeclKind - The TagKind enum. |
2953 | unsigned TagDeclKind : 3; |
2954 | |
2955 | /// IsCompleteDefinition - True if this is a definition ("struct foo |
2956 | /// {};"), false if it is a declaration ("struct foo;"). It is not |
2957 | /// a definition until the definition has been fully processed. |
2958 | unsigned IsCompleteDefinition : 1; |
2959 | |
2960 | protected: |
2961 | /// IsBeingDefined - True if this is currently being defined. |
2962 | unsigned IsBeingDefined : 1; |
2963 | |
2964 | private: |
2965 | /// IsEmbeddedInDeclarator - True if this tag declaration is |
2966 | /// "embedded" (i.e., defined or declared for the very first time) |
2967 | /// in the syntax of a declarator. |
2968 | unsigned IsEmbeddedInDeclarator : 1; |
2969 | |
2970 | /// \brief True if this tag is free standing, e.g. "struct foo;". |
2971 | unsigned IsFreeStanding : 1; |
2972 | |
2973 | protected: |
2974 | // These are used by (and only defined for) EnumDecl. |
2975 | unsigned NumPositiveBits : 8; |
2976 | unsigned NumNegativeBits : 8; |
2977 | |
2978 | /// IsScoped - True if this tag declaration is a scoped enumeration. Only |
2979 | /// possible in C++11 mode. |
2980 | unsigned IsScoped : 1; |
2981 | |
2982 | /// IsScopedUsingClassTag - If this tag declaration is a scoped enum, |
2983 | /// then this is true if the scoped enum was declared using the class |
2984 | /// tag, false if it was declared with the struct tag. No meaning is |
2985 | /// associated if this tag declaration is not a scoped enum. |
2986 | unsigned IsScopedUsingClassTag : 1; |
2987 | |
2988 | /// IsFixed - True if this is an enumeration with fixed underlying type. Only |
2989 | /// possible in C++11, Microsoft extensions, or Objective C mode. |
2990 | unsigned IsFixed : 1; |
2991 | |
2992 | /// \brief Indicates whether it is possible for declarations of this kind |
2993 | /// to have an out-of-date definition. |
2994 | /// |
2995 | /// This option is only enabled when modules are enabled. |
2996 | unsigned MayHaveOutOfDateDef : 1; |
2997 | |
2998 | /// Has the full definition of this type been required by a use somewhere in |
2999 | /// the TU. |
3000 | unsigned IsCompleteDefinitionRequired : 1; |
3001 | |
3002 | private: |
3003 | SourceRange BraceRange; |
3004 | |
3005 | // A struct representing syntactic qualifier info, |
3006 | // to be used for the (uncommon) case of out-of-line declarations. |
3007 | using ExtInfo = QualifierInfo; |
3008 | |
3009 | /// \brief If the (out-of-line) tag declaration name |
3010 | /// is qualified, it points to the qualifier info (nns and range); |
3011 | /// otherwise, if the tag declaration is anonymous and it is part of |
3012 | /// a typedef or alias, it points to the TypedefNameDecl (used for mangling); |
3013 | /// otherwise, if the tag declaration is anonymous and it is used as a |
3014 | /// declaration specifier for variables, it points to the first VarDecl (used |
3015 | /// for mangling); |
3016 | /// otherwise, it is a null (TypedefNameDecl) pointer. |
3017 | llvm::PointerUnion<TypedefNameDecl *, ExtInfo *> TypedefNameDeclOrQualifier; |
3018 | |
3019 | bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo *>(); } |
3020 | ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo *>(); } |
3021 | const ExtInfo *getExtInfo() const { |
3022 | return TypedefNameDeclOrQualifier.get<ExtInfo *>(); |
3023 | } |
3024 | |
3025 | protected: |
3026 | TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC, |
3027 | SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl, |
3028 | SourceLocation StartL) |
3029 | : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C), |
3030 | TagDeclKind(TK), IsCompleteDefinition(false), IsBeingDefined(false), |
3031 | IsEmbeddedInDeclarator(false), IsFreeStanding(false), |
3032 | IsCompleteDefinitionRequired(false), |
3033 | TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) { |
3034 | assert((DK != Enum || TK == TTK_Enum) &&(static_cast <bool> ((DK != Enum || TK == TTK_Enum) && "EnumDecl not matched with TTK_Enum") ? void (0) : __assert_fail ("(DK != Enum || TK == TTK_Enum) && \"EnumDecl not matched with TTK_Enum\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 3035, __extension__ __PRETTY_FUNCTION__)) |
3035 | "EnumDecl not matched with TTK_Enum")(static_cast <bool> ((DK != Enum || TK == TTK_Enum) && "EnumDecl not matched with TTK_Enum") ? void (0) : __assert_fail ("(DK != Enum || TK == TTK_Enum) && \"EnumDecl not matched with TTK_Enum\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 3035, __extension__ __PRETTY_FUNCTION__)); |
3036 | setPreviousDecl(PrevDecl); |
3037 | } |
3038 | |
3039 | using redeclarable_base = Redeclarable<TagDecl>; |
3040 | |
3041 | TagDecl *getNextRedeclarationImpl() override { |
3042 | return getNextRedeclaration(); |
3043 | } |
3044 | |
3045 | TagDecl *getPreviousDeclImpl() override { |
3046 | return getPreviousDecl(); |
3047 | } |
3048 | |
3049 | TagDecl *getMostRecentDeclImpl() override { |
3050 | return getMostRecentDecl(); |
3051 | } |
3052 | |
3053 | /// @brief Completes the definition of this tag declaration. |
3054 | /// |
3055 | /// This is a helper function for derived classes. |
3056 | void completeDefinition(); |
3057 | |
3058 | public: |
3059 | friend class ASTDeclReader; |
3060 | friend class ASTDeclWriter; |
3061 | |
3062 | using redecl_range = redeclarable_base::redecl_range; |
3063 | using redecl_iterator = redeclarable_base::redecl_iterator; |
3064 | |
3065 | using redeclarable_base::redecls_begin; |
3066 | using redeclarable_base::redecls_end; |
3067 | using redeclarable_base::redecls; |
3068 | using redeclarable_base::getPreviousDecl; |
3069 | using redeclarable_base::getMostRecentDecl; |
3070 | using redeclarable_base::isFirstDecl; |
3071 | |
3072 | SourceRange getBraceRange() const { return BraceRange; } |
3073 | void setBraceRange(SourceRange R) { BraceRange = R; } |
3074 | |
3075 | /// getInnerLocStart - Return SourceLocation representing start of source |
3076 | /// range ignoring outer template declarations. |
3077 | SourceLocation getInnerLocStart() const { return getLocStart(); } |
3078 | |
3079 | /// getOuterLocStart - Return SourceLocation representing start of source |
3080 | /// range taking into account any outer template declarations. |
3081 | SourceLocation getOuterLocStart() const; |
3082 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
3083 | |
3084 | TagDecl *getCanonicalDecl() override; |
3085 | const TagDecl *getCanonicalDecl() const { |
3086 | return const_cast<TagDecl*>(this)->getCanonicalDecl(); |
3087 | } |
3088 | |
3089 | /// isThisDeclarationADefinition() - Return true if this declaration |
3090 | /// is a completion definition of the type. Provided for consistency. |
3091 | bool isThisDeclarationADefinition() const { |
3092 | return isCompleteDefinition(); |
3093 | } |
3094 | |
3095 | /// isCompleteDefinition - Return true if this decl has its body |
3096 | /// fully specified. |
3097 | bool isCompleteDefinition() const { |
3098 | return IsCompleteDefinition; |
3099 | } |
3100 | |
3101 | /// \brief Return true if this complete decl is |
3102 | /// required to be complete for some existing use. |
3103 | bool isCompleteDefinitionRequired() const { |
3104 | return IsCompleteDefinitionRequired; |
3105 | } |
3106 | |
3107 | /// isBeingDefined - Return true if this decl is currently being defined. |
3108 | bool isBeingDefined() const { |
3109 | return IsBeingDefined; |
3110 | } |
3111 | |
3112 | bool isEmbeddedInDeclarator() const { |
3113 | return IsEmbeddedInDeclarator; |
3114 | } |
3115 | void setEmbeddedInDeclarator(bool isInDeclarator) { |
3116 | IsEmbeddedInDeclarator = isInDeclarator; |
3117 | } |
3118 | |
3119 | bool isFreeStanding() const { return IsFreeStanding; } |
3120 | void setFreeStanding(bool isFreeStanding = true) { |
3121 | IsFreeStanding = isFreeStanding; |
3122 | } |
3123 | |
3124 | /// \brief Whether this declaration declares a type that is |
3125 | /// dependent, i.e., a type that somehow depends on template |
3126 | /// parameters. |
3127 | bool isDependentType() const { return isDependentContext(); } |
3128 | |
3129 | /// @brief Starts the definition of this tag declaration. |
3130 | /// |
3131 | /// This method should be invoked at the beginning of the definition |
3132 | /// of this tag declaration. It will set the tag type into a state |
3133 | /// where it is in the process of being defined. |
3134 | void startDefinition(); |
3135 | |
3136 | /// getDefinition - Returns the TagDecl that actually defines this |
3137 | /// struct/union/class/enum. When determining whether or not a |
3138 | /// struct/union/class/enum has a definition, one should use this |
3139 | /// method as opposed to 'isDefinition'. 'isDefinition' indicates |
3140 | /// whether or not a specific TagDecl is defining declaration, not |
3141 | /// whether or not the struct/union/class/enum type is defined. |
3142 | /// This method returns NULL if there is no TagDecl that defines |
3143 | /// the struct/union/class/enum. |
3144 | TagDecl *getDefinition() const; |
3145 | |
3146 | void setCompleteDefinition(bool V) { IsCompleteDefinition = V; } |
3147 | |
3148 | void setCompleteDefinitionRequired(bool V = true) { |
3149 | IsCompleteDefinitionRequired = V; |
3150 | } |
3151 | |
3152 | StringRef getKindName() const { |
3153 | return TypeWithKeyword::getTagTypeKindName(getTagKind()); |
3154 | } |
3155 | |
3156 | TagKind getTagKind() const { |
3157 | return TagKind(TagDeclKind); |
3158 | } |
3159 | |
3160 | void setTagKind(TagKind TK) { TagDeclKind = TK; } |
3161 | |
3162 | bool isStruct() const { return getTagKind() == TTK_Struct; } |
3163 | bool isInterface() const { return getTagKind() == TTK_Interface; } |
3164 | bool isClass() const { return getTagKind() == TTK_Class; } |
3165 | bool isUnion() const { return getTagKind() == TTK_Union; } |
3166 | bool isEnum() const { return getTagKind() == TTK_Enum; } |
3167 | |
3168 | /// Is this tag type named, either directly or via being defined in |
3169 | /// a typedef of this type? |
3170 | /// |
3171 | /// C++11 [basic.link]p8: |
3172 | /// A type is said to have linkage if and only if: |
3173 | /// - it is a class or enumeration type that is named (or has a |
3174 | /// name for linkage purposes) and the name has linkage; ... |
3175 | /// C++11 [dcl.typedef]p9: |
3176 | /// If the typedef declaration defines an unnamed class (or enum), |
3177 | /// the first typedef-name declared by the declaration to be that |
3178 | /// class type (or enum type) is used to denote the class type (or |
3179 | /// enum type) for linkage purposes only. |
3180 | /// |
3181 | /// C does not have an analogous rule, but the same concept is |
3182 | /// nonetheless useful in some places. |
3183 | bool hasNameForLinkage() const { |
3184 | return (getDeclName() || getTypedefNameForAnonDecl()); |
3185 | } |
3186 | |
3187 | TypedefNameDecl *getTypedefNameForAnonDecl() const { |
3188 | return hasExtInfo() ? nullptr |
3189 | : TypedefNameDeclOrQualifier.get<TypedefNameDecl *>(); |
3190 | } |
3191 | |
3192 | void setTypedefNameForAnonDecl(TypedefNameDecl *TDD); |
3193 | |
3194 | /// \brief Retrieve the nested-name-specifier that qualifies the name of this |
3195 | /// declaration, if it was present in the source. |
3196 | NestedNameSpecifier *getQualifier() const { |
3197 | return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier() |
3198 | : nullptr; |
3199 | } |
3200 | |
3201 | /// \brief Retrieve the nested-name-specifier (with source-location |
3202 | /// information) that qualifies the name of this declaration, if it was |
3203 | /// present in the source. |
3204 | NestedNameSpecifierLoc getQualifierLoc() const { |
3205 | return hasExtInfo() ? getExtInfo()->QualifierLoc |
3206 | : NestedNameSpecifierLoc(); |
3207 | } |
3208 | |
3209 | void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc); |
3210 | |
3211 | unsigned getNumTemplateParameterLists() const { |
3212 | return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0; |
3213 | } |
3214 | |
3215 | TemplateParameterList *getTemplateParameterList(unsigned i) const { |
3216 | assert(i < getNumTemplateParameterLists())(static_cast <bool> (i < getNumTemplateParameterLists ()) ? void (0) : __assert_fail ("i < getNumTemplateParameterLists()" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 3216, __extension__ __PRETTY_FUNCTION__)); |
3217 | return getExtInfo()->TemplParamLists[i]; |
3218 | } |
3219 | |
3220 | void setTemplateParameterListsInfo(ASTContext &Context, |
3221 | ArrayRef<TemplateParameterList *> TPLists); |
3222 | |
3223 | // Implement isa/cast/dyncast/etc. |
3224 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3225 | static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; } |
3226 | |
3227 | static DeclContext *castToDeclContext(const TagDecl *D) { |
3228 | return static_cast<DeclContext *>(const_cast<TagDecl*>(D)); |
3229 | } |
3230 | |
3231 | static TagDecl *castFromDeclContext(const DeclContext *DC) { |
3232 | return static_cast<TagDecl *>(const_cast<DeclContext*>(DC)); |
3233 | } |
3234 | }; |
3235 | |
3236 | /// EnumDecl - Represents an enum. In C++11, enums can be forward-declared |
3237 | /// with a fixed underlying type, and in C we allow them to be forward-declared |
3238 | /// with no underlying type as an extension. |
3239 | class EnumDecl : public TagDecl { |
3240 | /// IntegerType - This represent the integer type that the enum corresponds |
3241 | /// to for code generation purposes. Note that the enumerator constants may |
3242 | /// have a different type than this does. |
3243 | /// |
3244 | /// If the underlying integer type was explicitly stated in the source |
3245 | /// code, this is a TypeSourceInfo* for that type. Otherwise this type |
3246 | /// was automatically deduced somehow, and this is a Type*. |
3247 | /// |
3248 | /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in |
3249 | /// some cases it won't. |
3250 | /// |
3251 | /// The underlying type of an enumeration never has any qualifiers, so |
3252 | /// we can get away with just storing a raw Type*, and thus save an |
3253 | /// extra pointer when TypeSourceInfo is needed. |
3254 | llvm::PointerUnion<const Type *, TypeSourceInfo *> IntegerType; |
3255 | |
3256 | /// PromotionType - The integer type that values of this type should |
3257 | /// promote to. In C, enumerators are generally of an integer type |
3258 | /// directly, but gcc-style large enumerators (and all enumerators |
3259 | /// in C++) are of the enum type instead. |
3260 | QualType PromotionType; |
3261 | |
3262 | /// \brief If this enumeration is an instantiation of a member enumeration |
3263 | /// of a class template specialization, this is the member specialization |
3264 | /// information. |
3265 | MemberSpecializationInfo *SpecializationInfo = nullptr; |
3266 | |
3267 | EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
3268 | SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, |
3269 | bool Scoped, bool ScopedUsingClassTag, bool Fixed) |
3270 | : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) { |
3271 | assert(Scoped || !ScopedUsingClassTag)(static_cast <bool> (Scoped || !ScopedUsingClassTag) ? void (0) : __assert_fail ("Scoped || !ScopedUsingClassTag", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 3271, __extension__ __PRETTY_FUNCTION__)); |
3272 | IntegerType = (const Type *)nullptr; |
3273 | NumNegativeBits = 0; |
3274 | NumPositiveBits = 0; |
3275 | IsScoped = Scoped; |
3276 | IsScopedUsingClassTag = ScopedUsingClassTag; |
3277 | IsFixed = Fixed; |
3278 | } |
3279 | |
3280 | void anchor() override; |
3281 | |
3282 | void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED, |
3283 | TemplateSpecializationKind TSK); |
3284 | public: |
3285 | friend class ASTDeclReader; |
3286 | |
3287 | EnumDecl *getCanonicalDecl() override { |
3288 | return cast<EnumDecl>(TagDecl::getCanonicalDecl()); |
3289 | } |
3290 | const EnumDecl *getCanonicalDecl() const { |
3291 | return const_cast<EnumDecl*>(this)->getCanonicalDecl(); |
3292 | } |
3293 | |
3294 | EnumDecl *getPreviousDecl() { |
3295 | return cast_or_null<EnumDecl>( |
3296 | static_cast<TagDecl *>(this)->getPreviousDecl()); |
3297 | } |
3298 | const EnumDecl *getPreviousDecl() const { |
3299 | return const_cast<EnumDecl*>(this)->getPreviousDecl(); |
3300 | } |
3301 | |
3302 | EnumDecl *getMostRecentDecl() { |
3303 | return cast<EnumDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl()); |
3304 | } |
3305 | const EnumDecl *getMostRecentDecl() const { |
3306 | return const_cast<EnumDecl*>(this)->getMostRecentDecl(); |
3307 | } |
3308 | |
3309 | EnumDecl *getDefinition() const { |
3310 | return cast_or_null<EnumDecl>(TagDecl::getDefinition()); |
3311 | } |
3312 | |
3313 | static EnumDecl *Create(ASTContext &C, DeclContext *DC, |
3314 | SourceLocation StartLoc, SourceLocation IdLoc, |
3315 | IdentifierInfo *Id, EnumDecl *PrevDecl, |
3316 | bool IsScoped, bool IsScopedUsingClassTag, |
3317 | bool IsFixed); |
3318 | static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
3319 | |
3320 | /// completeDefinition - When created, the EnumDecl corresponds to a |
3321 | /// forward-declared enum. This method is used to mark the |
3322 | /// declaration as being defined; it's enumerators have already been |
3323 | /// added (via DeclContext::addDecl). NewType is the new underlying |
3324 | /// type of the enumeration type. |
3325 | void completeDefinition(QualType NewType, |
3326 | QualType PromotionType, |
3327 | unsigned NumPositiveBits, |
3328 | unsigned NumNegativeBits); |
3329 | |
3330 | // enumerator_iterator - Iterates through the enumerators of this |
3331 | // enumeration. |
3332 | using enumerator_iterator = specific_decl_iterator<EnumConstantDecl>; |
3333 | using enumerator_range = |
3334 | llvm::iterator_range<specific_decl_iterator<EnumConstantDecl>>; |
3335 | |
3336 | enumerator_range enumerators() const { |
3337 | return enumerator_range(enumerator_begin(), enumerator_end()); |
3338 | } |
3339 | |
3340 | enumerator_iterator enumerator_begin() const { |
3341 | const EnumDecl *E = getDefinition(); |
3342 | if (!E) |
3343 | E = this; |
3344 | return enumerator_iterator(E->decls_begin()); |
3345 | } |
3346 | |
3347 | enumerator_iterator enumerator_end() const { |
3348 | const EnumDecl *E = getDefinition(); |
3349 | if (!E) |
3350 | E = this; |
3351 | return enumerator_iterator(E->decls_end()); |
3352 | } |
3353 | |
3354 | /// getPromotionType - Return the integer type that enumerators |
3355 | /// should promote to. |
3356 | QualType getPromotionType() const { return PromotionType; } |
3357 | |
3358 | /// \brief Set the promotion type. |
3359 | void setPromotionType(QualType T) { PromotionType = T; } |
3360 | |
3361 | /// getIntegerType - Return the integer type this enum decl corresponds to. |
3362 | /// This returns a null QualType for an enum forward definition with no fixed |
3363 | /// underlying type. |
3364 | QualType getIntegerType() const { |
3365 | if (!IntegerType) |
3366 | return QualType(); |
3367 | if (const Type *T = IntegerType.dyn_cast<const Type*>()) |
3368 | return QualType(T, 0); |
3369 | return IntegerType.get<TypeSourceInfo*>()->getType().getUnqualifiedType(); |
3370 | } |
3371 | |
3372 | /// \brief Set the underlying integer type. |
3373 | void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); } |
3374 | |
3375 | /// \brief Set the underlying integer type source info. |
3376 | void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo) { IntegerType = TInfo; } |
3377 | |
3378 | /// \brief Return the type source info for the underlying integer type, |
3379 | /// if no type source info exists, return 0. |
3380 | TypeSourceInfo *getIntegerTypeSourceInfo() const { |
3381 | return IntegerType.dyn_cast<TypeSourceInfo*>(); |
3382 | } |
3383 | |
3384 | /// \brief Retrieve the source range that covers the underlying type if |
3385 | /// specified. |
3386 | SourceRange getIntegerTypeRange() const LLVM_READONLY__attribute__((__pure__)); |
3387 | |
3388 | /// \brief Returns the width in bits required to store all the |
3389 | /// non-negative enumerators of this enum. |
3390 | unsigned getNumPositiveBits() const { |
3391 | return NumPositiveBits; |
3392 | } |
3393 | void setNumPositiveBits(unsigned Num) { |
3394 | NumPositiveBits = Num; |
3395 | assert(NumPositiveBits == Num && "can't store this bitcount")(static_cast <bool> (NumPositiveBits == Num && "can't store this bitcount" ) ? void (0) : __assert_fail ("NumPositiveBits == Num && \"can't store this bitcount\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 3395, __extension__ __PRETTY_FUNCTION__)); |
3396 | } |
3397 | |
3398 | /// \brief Returns the width in bits required to store all the |
3399 | /// negative enumerators of this enum. These widths include |
3400 | /// the rightmost leading 1; that is: |
3401 | /// |
3402 | /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS |
3403 | /// ------------------------ ------- ----------------- |
3404 | /// -1 1111111 1 |
3405 | /// -10 1110110 5 |
3406 | /// -101 1001011 8 |
3407 | unsigned getNumNegativeBits() const { |
3408 | return NumNegativeBits; |
3409 | } |
3410 | void setNumNegativeBits(unsigned Num) { |
3411 | NumNegativeBits = Num; |
3412 | } |
3413 | |
3414 | /// \brief Returns true if this is a C++11 scoped enumeration. |
3415 | bool isScoped() const { |
3416 | return IsScoped; |
3417 | } |
3418 | |
3419 | /// \brief Returns true if this is a C++11 scoped enumeration. |
3420 | bool isScopedUsingClassTag() const { |
3421 | return IsScopedUsingClassTag; |
3422 | } |
3423 | |
3424 | /// \brief Returns true if this is an Objective-C, C++11, or |
3425 | /// Microsoft-style enumeration with a fixed underlying type. |
3426 | bool isFixed() const { |
3427 | return IsFixed; |
3428 | } |
3429 | |
3430 | /// \brief Returns true if this can be considered a complete type. |
3431 | bool isComplete() const { |
3432 | return isCompleteDefinition() || isFixed(); |
3433 | } |
3434 | |
3435 | /// Returns true if this enum is either annotated with |
3436 | /// enum_extensibility(closed) or isn't annotated with enum_extensibility. |
3437 | bool isClosed() const; |
3438 | |
3439 | /// Returns true if this enum is annotated with flag_enum and isn't annotated |
3440 | /// with enum_extensibility(open). |
3441 | bool isClosedFlag() const; |
3442 | |
3443 | /// Returns true if this enum is annotated with neither flag_enum nor |
3444 | /// enum_extensibility(open). |
3445 | bool isClosedNonFlag() const; |
3446 | |
3447 | /// \brief Retrieve the enum definition from which this enumeration could |
3448 | /// be instantiated, if it is an instantiation (rather than a non-template). |
3449 | EnumDecl *getTemplateInstantiationPattern() const; |
3450 | |
3451 | /// \brief Returns the enumeration (declared within the template) |
3452 | /// from which this enumeration type was instantiated, or NULL if |
3453 | /// this enumeration was not instantiated from any template. |
3454 | EnumDecl *getInstantiatedFromMemberEnum() const; |
3455 | |
3456 | /// \brief If this enumeration is a member of a specialization of a |
3457 | /// templated class, determine what kind of template specialization |
3458 | /// or instantiation this is. |
3459 | TemplateSpecializationKind getTemplateSpecializationKind() const; |
3460 | |
3461 | /// \brief For an enumeration member that was instantiated from a member |
3462 | /// enumeration of a templated class, set the template specialiation kind. |
3463 | void setTemplateSpecializationKind(TemplateSpecializationKind TSK, |
3464 | SourceLocation PointOfInstantiation = SourceLocation()); |
3465 | |
3466 | /// \brief If this enumeration is an instantiation of a member enumeration of |
3467 | /// a class template specialization, retrieves the member specialization |
3468 | /// information. |
3469 | MemberSpecializationInfo *getMemberSpecializationInfo() const { |
3470 | return SpecializationInfo; |
3471 | } |
3472 | |
3473 | /// \brief Specify that this enumeration is an instantiation of the |
3474 | /// member enumeration ED. |
3475 | void setInstantiationOfMemberEnum(EnumDecl *ED, |
3476 | TemplateSpecializationKind TSK) { |
3477 | setInstantiationOfMemberEnum(getASTContext(), ED, TSK); |
3478 | } |
3479 | |
3480 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3481 | static bool classofKind(Kind K) { return K == Enum; } |
3482 | }; |
3483 | |
3484 | /// RecordDecl - Represents a struct/union/class. For example: |
3485 | /// struct X; // Forward declaration, no "body". |
3486 | /// union Y { int A, B; }; // Has body with members A and B (FieldDecls). |
3487 | /// This decl will be marked invalid if *any* members are invalid. |
3488 | class RecordDecl : public TagDecl { |
3489 | friend class DeclContext; |
3490 | |
3491 | // FIXME: This can be packed into the bitfields in Decl. |
3492 | /// HasFlexibleArrayMember - This is true if this struct ends with a flexible |
3493 | /// array member (e.g. int X[]) or if this union contains a struct that does. |
3494 | /// If so, this cannot be contained in arrays or other structs as a member. |
3495 | bool HasFlexibleArrayMember : 1; |
3496 | |
3497 | /// AnonymousStructOrUnion - Whether this is the type of an anonymous struct |
3498 | /// or union. |
3499 | bool AnonymousStructOrUnion : 1; |
3500 | |
3501 | /// HasObjectMember - This is true if this struct has at least one member |
3502 | /// containing an Objective-C object pointer type. |
3503 | bool HasObjectMember : 1; |
3504 | |
3505 | /// HasVolatileMember - This is true if struct has at least one member of |
3506 | /// 'volatile' type. |
3507 | bool HasVolatileMember : 1; |
3508 | |
3509 | /// \brief Whether the field declarations of this record have been loaded |
3510 | /// from external storage. To avoid unnecessary deserialization of |
3511 | /// methods/nested types we allow deserialization of just the fields |
3512 | /// when needed. |
3513 | mutable bool LoadedFieldsFromExternalStorage : 1; |
3514 | |
3515 | protected: |
3516 | RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC, |
3517 | SourceLocation StartLoc, SourceLocation IdLoc, |
3518 | IdentifierInfo *Id, RecordDecl *PrevDecl); |
3519 | |
3520 | public: |
3521 | static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC, |
3522 | SourceLocation StartLoc, SourceLocation IdLoc, |
3523 | IdentifierInfo *Id, RecordDecl* PrevDecl = nullptr); |
3524 | static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID); |
3525 | |
3526 | RecordDecl *getPreviousDecl() { |
3527 | return cast_or_null<RecordDecl>( |
3528 | static_cast<TagDecl *>(this)->getPreviousDecl()); |
3529 | } |
3530 | const RecordDecl *getPreviousDecl() const { |
3531 | return const_cast<RecordDecl*>(this)->getPreviousDecl(); |
3532 | } |
3533 | |
3534 | RecordDecl *getMostRecentDecl() { |
3535 | return cast<RecordDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl()); |
3536 | } |
3537 | const RecordDecl *getMostRecentDecl() const { |
3538 | return const_cast<RecordDecl*>(this)->getMostRecentDecl(); |
3539 | } |
3540 | |
3541 | bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; } |
3542 | void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; } |
3543 | |
3544 | /// isAnonymousStructOrUnion - Whether this is an anonymous struct |
3545 | /// or union. To be an anonymous struct or union, it must have been |
3546 | /// declared without a name and there must be no objects of this |
3547 | /// type declared, e.g., |
3548 | /// @code |
3549 | /// union { int i; float f; }; |
3550 | /// @endcode |
3551 | /// is an anonymous union but neither of the following are: |
3552 | /// @code |
3553 | /// union X { int i; float f; }; |
3554 | /// union { int i; float f; } obj; |
3555 | /// @endcode |
3556 | bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; } |
3557 | void setAnonymousStructOrUnion(bool Anon) { |
3558 | AnonymousStructOrUnion = Anon; |
3559 | } |
3560 | |
3561 | bool hasObjectMember() const { return HasObjectMember; } |
3562 | void setHasObjectMember (bool val) { HasObjectMember = val; } |
3563 | |
3564 | bool hasVolatileMember() const { return HasVolatileMember; } |
3565 | void setHasVolatileMember (bool val) { HasVolatileMember = val; } |
3566 | |
3567 | bool hasLoadedFieldsFromExternalStorage() const { |
3568 | return LoadedFieldsFromExternalStorage; |
3569 | } |
3570 | void setHasLoadedFieldsFromExternalStorage(bool val) { |
3571 | LoadedFieldsFromExternalStorage = val; |
3572 | } |
3573 | |
3574 | /// \brief Determines whether this declaration represents the |
3575 | /// injected class name. |
3576 | /// |
3577 | /// The injected class name in C++ is the name of the class that |
3578 | /// appears inside the class itself. For example: |
3579 | /// |
3580 | /// \code |
3581 | /// struct C { |
3582 | /// // C is implicitly declared here as a synonym for the class name. |
3583 | /// }; |
3584 | /// |
3585 | /// C::C c; // same as "C c;" |
3586 | /// \endcode |
3587 | bool isInjectedClassName() const; |
3588 | |
3589 | /// \brief Determine whether this record is a class describing a lambda |
3590 | /// function object. |
3591 | bool isLambda() const; |
3592 | |
3593 | /// \brief Determine whether this record is a record for captured variables in |
3594 | /// CapturedStmt construct. |
3595 | bool isCapturedRecord() const; |
3596 | |
3597 | /// \brief Mark the record as a record for captured variables in CapturedStmt |
3598 | /// construct. |
3599 | void setCapturedRecord(); |
3600 | |
3601 | /// getDefinition - Returns the RecordDecl that actually defines |
3602 | /// this struct/union/class. When determining whether or not a |
3603 | /// struct/union/class is completely defined, one should use this |
3604 | /// method as opposed to 'isCompleteDefinition'. |
3605 | /// 'isCompleteDefinition' indicates whether or not a specific |
3606 | /// RecordDecl is a completed definition, not whether or not the |
3607 | /// record type is defined. This method returns NULL if there is |
3608 | /// no RecordDecl that defines the struct/union/tag. |
3609 | RecordDecl *getDefinition() const { |
3610 | return cast_or_null<RecordDecl>(TagDecl::getDefinition()); |
3611 | } |
3612 | |
3613 | // Iterator access to field members. The field iterator only visits |
3614 | // the non-static data members of this class, ignoring any static |
3615 | // data members, functions, constructors, destructors, etc. |
3616 | using field_iterator = specific_decl_iterator<FieldDecl>; |
3617 | using field_range = llvm::iterator_range<specific_decl_iterator<FieldDecl>>; |
3618 | |
3619 | field_range fields() const { return field_range(field_begin(), field_end()); } |
3620 | field_iterator field_begin() const; |
3621 | |
3622 | field_iterator field_end() const { |
3623 | return field_iterator(decl_iterator()); |
3624 | } |
3625 | |
3626 | // field_empty - Whether there are any fields (non-static data |
3627 | // members) in this record. |
3628 | bool field_empty() const { |
3629 | return field_begin() == field_end(); |
3630 | } |
3631 | |
3632 | /// completeDefinition - Notes that the definition of this type is |
3633 | /// now complete. |
3634 | virtual void completeDefinition(); |
3635 | |
3636 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3637 | static bool classofKind(Kind K) { |
3638 | return K >= firstRecord && K <= lastRecord; |
3639 | } |
3640 | |
3641 | /// \brief Get whether or not this is an ms_struct which can |
3642 | /// be turned on with an attribute, pragma, or -mms-bitfields |
3643 | /// commandline option. |
3644 | bool isMsStruct(const ASTContext &C) const; |
3645 | |
3646 | /// \brief Whether we are allowed to insert extra padding between fields. |
3647 | /// These padding are added to help AddressSanitizer detect |
3648 | /// intra-object-overflow bugs. |
3649 | bool mayInsertExtraPadding(bool EmitRemark = false) const; |
3650 | |
3651 | /// Finds the first data member which has a name. |
3652 | /// nullptr is returned if no named data member exists. |
3653 | const FieldDecl *findFirstNamedDataMember() const; |
3654 | |
3655 | private: |
3656 | /// \brief Deserialize just the fields. |
3657 | void LoadFieldsFromExternalStorage() const; |
3658 | }; |
3659 | |
3660 | class FileScopeAsmDecl : public Decl { |
3661 | StringLiteral *AsmString; |
3662 | SourceLocation RParenLoc; |
3663 | |
3664 | FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring, |
3665 | SourceLocation StartL, SourceLocation EndL) |
3666 | : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {} |
3667 | |
3668 | virtual void anchor(); |
3669 | |
3670 | public: |
3671 | static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC, |
3672 | StringLiteral *Str, SourceLocation AsmLoc, |
3673 | SourceLocation RParenLoc); |
3674 | |
3675 | static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
3676 | |
3677 | SourceLocation getAsmLoc() const { return getLocation(); } |
3678 | SourceLocation getRParenLoc() const { return RParenLoc; } |
3679 | void setRParenLoc(SourceLocation L) { RParenLoc = L; } |
3680 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
3681 | return SourceRange(getAsmLoc(), getRParenLoc()); |
3682 | } |
3683 | |
3684 | const StringLiteral *getAsmString() const { return AsmString; } |
3685 | StringLiteral *getAsmString() { return AsmString; } |
3686 | void setAsmString(StringLiteral *Asm) { AsmString = Asm; } |
3687 | |
3688 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3689 | static bool classofKind(Kind K) { return K == FileScopeAsm; } |
3690 | }; |
3691 | |
3692 | /// BlockDecl - This represents a block literal declaration, which is like an |
3693 | /// unnamed FunctionDecl. For example: |
3694 | /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body } |
3695 | class BlockDecl : public Decl, public DeclContext { |
3696 | public: |
3697 | /// A class which contains all the information about a particular |
3698 | /// captured value. |
3699 | class Capture { |
3700 | enum { |
3701 | flag_isByRef = 0x1, |
3702 | flag_isNested = 0x2 |
3703 | }; |
3704 | |
3705 | /// The variable being captured. |
3706 | llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags; |
3707 | |
3708 | /// The copy expression, expressed in terms of a DeclRef (or |
3709 | /// BlockDeclRef) to the captured variable. Only required if the |
3710 | /// variable has a C++ class type. |
3711 | Expr *CopyExpr; |
3712 | |
3713 | public: |
3714 | Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy) |
3715 | : VariableAndFlags(variable, |
3716 | (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)), |
3717 | CopyExpr(copy) {} |
3718 | |
3719 | /// The variable being captured. |
3720 | VarDecl *getVariable() const { return VariableAndFlags.getPointer(); } |
3721 | |
3722 | /// Whether this is a "by ref" capture, i.e. a capture of a __block |
3723 | /// variable. |
3724 | bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; } |
3725 | |
3726 | /// Whether this is a nested capture, i.e. the variable captured |
3727 | /// is not from outside the immediately enclosing function/block. |
3728 | bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; } |
3729 | |
3730 | bool hasCopyExpr() const { return CopyExpr != nullptr; } |
3731 | Expr *getCopyExpr() const { return CopyExpr; } |
3732 | void setCopyExpr(Expr *e) { CopyExpr = e; } |
3733 | }; |
3734 | |
3735 | private: |
3736 | // FIXME: This can be packed into the bitfields in Decl. |
3737 | bool IsVariadic : 1; |
3738 | bool CapturesCXXThis : 1; |
3739 | bool BlockMissingReturnType : 1; |
3740 | bool IsConversionFromLambda : 1; |
3741 | |
3742 | /// ParamInfo - new[]'d array of pointers to ParmVarDecls for the formal |
3743 | /// parameters of this function. This is null if a prototype or if there are |
3744 | /// no formals. |
3745 | ParmVarDecl **ParamInfo = nullptr; |
3746 | unsigned NumParams = 0; |
3747 | |
3748 | Stmt *Body = nullptr; |
3749 | TypeSourceInfo *SignatureAsWritten = nullptr; |
3750 | |
3751 | const Capture *Captures = nullptr; |
3752 | unsigned NumCaptures = 0; |
3753 | |
3754 | unsigned ManglingNumber = 0; |
3755 | Decl *ManglingContextDecl = nullptr; |
3756 | |
3757 | protected: |
3758 | BlockDecl(DeclContext *DC, SourceLocation CaretLoc) |
3759 | : Decl(Block, DC, CaretLoc), DeclContext(Block), IsVariadic(false), |
3760 | CapturesCXXThis(false), BlockMissingReturnType(true), |
3761 | IsConversionFromLambda(false) {} |
3762 | |
3763 | public: |
3764 | static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L); |
3765 | static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
3766 | |
3767 | SourceLocation getCaretLocation() const { return getLocation(); } |
3768 | |
3769 | bool isVariadic() const { return IsVariadic; } |
3770 | void setIsVariadic(bool value) { IsVariadic = value; } |
3771 | |
3772 | CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; } |
3773 | Stmt *getBody() const override { return (Stmt*) Body; } |
3774 | void setBody(CompoundStmt *B) { Body = (Stmt*) B; } |
3775 | |
3776 | void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; } |
3777 | TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; } |
3778 | |
3779 | // ArrayRef access to formal parameters. |
3780 | ArrayRef<ParmVarDecl *> parameters() const { |
3781 | return {ParamInfo, getNumParams()}; |
3782 | } |
3783 | MutableArrayRef<ParmVarDecl *> parameters() { |
3784 | return {ParamInfo, getNumParams()}; |
3785 | } |
3786 | |
3787 | // Iterator access to formal parameters. |
3788 | using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator; |
3789 | using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator; |
3790 | |
3791 | bool param_empty() const { return parameters().empty(); } |
3792 | param_iterator param_begin() { return parameters().begin(); } |
3793 | param_iterator param_end() { return parameters().end(); } |
3794 | param_const_iterator param_begin() const { return parameters().begin(); } |
3795 | param_const_iterator param_end() const { return parameters().end(); } |
3796 | size_t param_size() const { return parameters().size(); } |
3797 | |
3798 | unsigned getNumParams() const { return NumParams; } |
3799 | |
3800 | const ParmVarDecl *getParamDecl(unsigned i) const { |
3801 | assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #" ) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 3801, __extension__ __PRETTY_FUNCTION__)); |
3802 | return ParamInfo[i]; |
3803 | } |
3804 | ParmVarDecl *getParamDecl(unsigned i) { |
3805 | assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #" ) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 3805, __extension__ __PRETTY_FUNCTION__)); |
3806 | return ParamInfo[i]; |
3807 | } |
3808 | |
3809 | void setParams(ArrayRef<ParmVarDecl *> NewParamInfo); |
3810 | |
3811 | /// hasCaptures - True if this block (or its nested blocks) captures |
3812 | /// anything of local storage from its enclosing scopes. |
3813 | bool hasCaptures() const { return NumCaptures != 0 || CapturesCXXThis; } |
3814 | |
3815 | /// getNumCaptures - Returns the number of captured variables. |
3816 | /// Does not include an entry for 'this'. |
3817 | unsigned getNumCaptures() const { return NumCaptures; } |
3818 | |
3819 | using capture_const_iterator = ArrayRef<Capture>::const_iterator; |
3820 | |
3821 | ArrayRef<Capture> captures() const { return {Captures, NumCaptures}; } |
3822 | |
3823 | capture_const_iterator capture_begin() const { return captures().begin(); } |
3824 | capture_const_iterator capture_end() const { return captures().end(); } |
3825 | |
3826 | bool capturesCXXThis() const { return CapturesCXXThis; } |
3827 | bool blockMissingReturnType() const { return BlockMissingReturnType; } |
3828 | void setBlockMissingReturnType(bool val) { BlockMissingReturnType = val; } |
3829 | |
3830 | bool isConversionFromLambda() const { return IsConversionFromLambda; } |
3831 | void setIsConversionFromLambda(bool val) { IsConversionFromLambda = val; } |
3832 | |
3833 | bool capturesVariable(const VarDecl *var) const; |
3834 | |
3835 | void setCaptures(ASTContext &Context, ArrayRef<Capture> Captures, |
3836 | bool CapturesCXXThis); |
3837 | |
3838 | unsigned getBlockManglingNumber() const { |
3839 | return ManglingNumber; |
3840 | } |
3841 | |
3842 | Decl *getBlockManglingContextDecl() const { |
3843 | return ManglingContextDecl; |
3844 | } |
3845 | |
3846 | void setBlockMangling(unsigned Number, Decl *Ctx) { |
3847 | ManglingNumber = Number; |
3848 | ManglingContextDecl = Ctx; |
3849 | } |
3850 | |
3851 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
3852 | |
3853 | // Implement isa/cast/dyncast/etc. |
3854 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3855 | static bool classofKind(Kind K) { return K == Block; } |
3856 | static DeclContext *castToDeclContext(const BlockDecl *D) { |
3857 | return static_cast<DeclContext *>(const_cast<BlockDecl*>(D)); |
3858 | } |
3859 | static BlockDecl *castFromDeclContext(const DeclContext *DC) { |
3860 | return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC)); |
3861 | } |
3862 | }; |
3863 | |
3864 | /// \brief This represents the body of a CapturedStmt, and serves as its |
3865 | /// DeclContext. |
3866 | class CapturedDecl final |
3867 | : public Decl, |
3868 | public DeclContext, |
3869 | private llvm::TrailingObjects<CapturedDecl, ImplicitParamDecl *> { |
3870 | protected: |
3871 | size_t numTrailingObjects(OverloadToken<ImplicitParamDecl>) { |
3872 | return NumParams; |
3873 | } |
3874 | |
3875 | private: |
3876 | /// \brief The number of parameters to the outlined function. |
3877 | unsigned NumParams; |
3878 | |
3879 | /// \brief The position of context parameter in list of parameters. |
3880 | unsigned ContextParam; |
3881 | |
3882 | /// \brief The body of the outlined function. |
3883 | llvm::PointerIntPair<Stmt *, 1, bool> BodyAndNothrow; |
3884 | |
3885 | explicit CapturedDecl(DeclContext *DC, unsigned NumParams); |
3886 | |
3887 | ImplicitParamDecl *const *getParams() const { |
3888 | return getTrailingObjects<ImplicitParamDecl *>(); |
3889 | } |
3890 | |
3891 | ImplicitParamDecl **getParams() { |
3892 | return getTrailingObjects<ImplicitParamDecl *>(); |
3893 | } |
3894 | |
3895 | public: |
3896 | friend class ASTDeclReader; |
3897 | friend class ASTDeclWriter; |
3898 | friend TrailingObjects; |
3899 | |
3900 | static CapturedDecl *Create(ASTContext &C, DeclContext *DC, |
3901 | unsigned NumParams); |
3902 | static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID, |
3903 | unsigned NumParams); |
3904 | |
3905 | Stmt *getBody() const override; |
3906 | void setBody(Stmt *B); |
3907 | |
3908 | bool isNothrow() const; |
3909 | void setNothrow(bool Nothrow = true); |
3910 | |
3911 | unsigned getNumParams() const { return NumParams; } |
3912 | |
3913 | ImplicitParamDecl *getParam(unsigned i) const { |
3914 | assert(i < NumParams)(static_cast <bool> (i < NumParams) ? void (0) : __assert_fail ("i < NumParams", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 3914, __extension__ __PRETTY_FUNCTION__)); |
3915 | return getParams()[i]; |
3916 | } |
3917 | void setParam(unsigned i, ImplicitParamDecl *P) { |
3918 | assert(i < NumParams)(static_cast <bool> (i < NumParams) ? void (0) : __assert_fail ("i < NumParams", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 3918, __extension__ __PRETTY_FUNCTION__)); |
3919 | getParams()[i] = P; |
3920 | } |
3921 | |
3922 | // ArrayRef interface to parameters. |
3923 | ArrayRef<ImplicitParamDecl *> parameters() const { |
3924 | return {getParams(), getNumParams()}; |
3925 | } |
3926 | MutableArrayRef<ImplicitParamDecl *> parameters() { |
3927 | return {getParams(), getNumParams()}; |
3928 | } |
3929 | |
3930 | /// \brief Retrieve the parameter containing captured variables. |
3931 | ImplicitParamDecl *getContextParam() const { |
3932 | assert(ContextParam < NumParams)(static_cast <bool> (ContextParam < NumParams) ? void (0) : __assert_fail ("ContextParam < NumParams", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 3932, __extension__ __PRETTY_FUNCTION__)); |
3933 | return getParam(ContextParam); |
3934 | } |
3935 | void setContextParam(unsigned i, ImplicitParamDecl *P) { |
3936 | assert(i < NumParams)(static_cast <bool> (i < NumParams) ? void (0) : __assert_fail ("i < NumParams", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 3936, __extension__ __PRETTY_FUNCTION__)); |
3937 | ContextParam = i; |
3938 | setParam(i, P); |
3939 | } |
3940 | unsigned getContextParamPosition() const { return ContextParam; } |
3941 | |
3942 | using param_iterator = ImplicitParamDecl *const *; |
3943 | using param_range = llvm::iterator_range<param_iterator>; |
3944 | |
3945 | /// \brief Retrieve an iterator pointing to the first parameter decl. |
3946 | param_iterator param_begin() const { return getParams(); } |
3947 | /// \brief Retrieve an iterator one past the last parameter decl. |
3948 | param_iterator param_end() const { return getParams() + NumParams; } |
3949 | |
3950 | // Implement isa/cast/dyncast/etc. |
3951 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3952 | static bool classofKind(Kind K) { return K == Captured; } |
3953 | static DeclContext *castToDeclContext(const CapturedDecl *D) { |
3954 | return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D)); |
3955 | } |
3956 | static CapturedDecl *castFromDeclContext(const DeclContext *DC) { |
3957 | return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC)); |
3958 | } |
3959 | }; |
3960 | |
3961 | /// \brief Describes a module import declaration, which makes the contents |
3962 | /// of the named module visible in the current translation unit. |
3963 | /// |
3964 | /// An import declaration imports the named module (or submodule). For example: |
3965 | /// \code |
3966 | /// @import std.vector; |
3967 | /// \endcode |
3968 | /// |
3969 | /// Import declarations can also be implicitly generated from |
3970 | /// \#include/\#import directives. |
3971 | class ImportDecl final : public Decl, |
3972 | llvm::TrailingObjects<ImportDecl, SourceLocation> { |
3973 | friend class ASTContext; |
3974 | friend class ASTDeclReader; |
3975 | friend class ASTReader; |
3976 | friend TrailingObjects; |
3977 | |
3978 | /// \brief The imported module, along with a bit that indicates whether |
3979 | /// we have source-location information for each identifier in the module |
3980 | /// name. |
3981 | /// |
3982 | /// When the bit is false, we only have a single source location for the |
3983 | /// end of the import declaration. |
3984 | llvm::PointerIntPair<Module *, 1, bool> ImportedAndComplete; |
3985 | |
3986 | /// \brief The next import in the list of imports local to the translation |
3987 | /// unit being parsed (not loaded from an AST file). |
3988 | ImportDecl *NextLocalImport = nullptr; |
3989 | |
3990 | ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported, |
3991 | ArrayRef<SourceLocation> IdentifierLocs); |
3992 | |
3993 | ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported, |
3994 | SourceLocation EndLoc); |
3995 | |
3996 | ImportDecl(EmptyShell Empty) : Decl(Import, Empty) {} |
3997 | |
3998 | public: |
3999 | /// \brief Create a new module import declaration. |
4000 | static ImportDecl *Create(ASTContext &C, DeclContext *DC, |
4001 | SourceLocation StartLoc, Module *Imported, |
4002 | ArrayRef<SourceLocation> IdentifierLocs); |
4003 | |
4004 | /// \brief Create a new module import declaration for an implicitly-generated |
4005 | /// import. |
4006 | static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC, |
4007 | SourceLocation StartLoc, Module *Imported, |
4008 | SourceLocation EndLoc); |
4009 | |
4010 | /// \brief Create a new, deserialized module import declaration. |
4011 | static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID, |
4012 | unsigned NumLocations); |
4013 | |
4014 | /// \brief Retrieve the module that was imported by the import declaration. |
4015 | Module *getImportedModule() const { return ImportedAndComplete.getPointer(); } |
4016 | |
4017 | /// \brief Retrieves the locations of each of the identifiers that make up |
4018 | /// the complete module name in the import declaration. |
4019 | /// |
4020 | /// This will return an empty array if the locations of the individual |
4021 | /// identifiers aren't available. |
4022 | ArrayRef<SourceLocation> getIdentifierLocs() const; |
4023 | |
4024 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
4025 | |
4026 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
4027 | static bool classofKind(Kind K) { return K == Import; } |
4028 | }; |
4029 | |
4030 | /// \brief Represents a C++ Modules TS module export declaration. |
4031 | /// |
4032 | /// For example: |
4033 | /// \code |
4034 | /// export void foo(); |
4035 | /// \endcode |
4036 | class ExportDecl final : public Decl, public DeclContext { |
4037 | virtual void anchor(); |
4038 | |
4039 | private: |
4040 | friend class ASTDeclReader; |
4041 | |
4042 | /// \brief The source location for the right brace (if valid). |
4043 | SourceLocation RBraceLoc; |
4044 | |
4045 | ExportDecl(DeclContext *DC, SourceLocation ExportLoc) |
4046 | : Decl(Export, DC, ExportLoc), DeclContext(Export), |
4047 | RBraceLoc(SourceLocation()) {} |
4048 | |
4049 | public: |
4050 | static ExportDecl *Create(ASTContext &C, DeclContext *DC, |
4051 | SourceLocation ExportLoc); |
4052 | static ExportDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
4053 | |
4054 | SourceLocation getExportLoc() const { return getLocation(); } |
4055 | SourceLocation getRBraceLoc() const { return RBraceLoc; } |
4056 | void setRBraceLoc(SourceLocation L) { RBraceLoc = L; } |
4057 | |
4058 | SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { |
4059 | if (RBraceLoc.isValid()) |
4060 | return RBraceLoc; |
4061 | // No braces: get the end location of the (only) declaration in context |
4062 | // (if present). |
4063 | return decls_empty() ? getLocation() : decls_begin()->getLocEnd(); |
4064 | } |
4065 | |
4066 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
4067 | return SourceRange(getLocation(), getLocEnd()); |
4068 | } |
4069 | |
4070 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
4071 | static bool classofKind(Kind K) { return K == Export; } |
4072 | static DeclContext *castToDeclContext(const ExportDecl *D) { |
4073 | return static_cast<DeclContext *>(const_cast<ExportDecl*>(D)); |
4074 | } |
4075 | static ExportDecl *castFromDeclContext(const DeclContext *DC) { |
4076 | return static_cast<ExportDecl *>(const_cast<DeclContext*>(DC)); |
4077 | } |
4078 | }; |
4079 | |
4080 | /// \brief Represents an empty-declaration. |
4081 | class EmptyDecl : public Decl { |
4082 | EmptyDecl(DeclContext *DC, SourceLocation L) : Decl(Empty, DC, L) {} |
4083 | |
4084 | virtual void anchor(); |
4085 | |
4086 | public: |
4087 | static EmptyDecl *Create(ASTContext &C, DeclContext *DC, |
4088 | SourceLocation L); |
4089 | static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
4090 | |
4091 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
4092 | static bool classofKind(Kind K) { return K == Empty; } |
4093 | }; |
4094 | |
4095 | /// Insertion operator for diagnostics. This allows sending NamedDecl's |
4096 | /// into a diagnostic with <<. |
4097 | inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, |
4098 | const NamedDecl* ND) { |
4099 | DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND), |
4100 | DiagnosticsEngine::ak_nameddecl); |
4101 | return DB; |
4102 | } |
4103 | inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, |
4104 | const NamedDecl* ND) { |
4105 | PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND), |
4106 | DiagnosticsEngine::ak_nameddecl); |
4107 | return PD; |
4108 | } |
4109 | |
4110 | template<typename decl_type> |
4111 | void Redeclarable<decl_type>::setPreviousDecl(decl_type *PrevDecl) { |
4112 | // Note: This routine is implemented here because we need both NamedDecl |
4113 | // and Redeclarable to be defined. |
4114 | assert(RedeclLink.NextIsLatest() &&(static_cast <bool> (RedeclLink.NextIsLatest() && "setPreviousDecl on a decl already in a redeclaration chain" ) ? void (0) : __assert_fail ("RedeclLink.NextIsLatest() && \"setPreviousDecl on a decl already in a redeclaration chain\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 4115, __extension__ __PRETTY_FUNCTION__)) |
4115 | "setPreviousDecl on a decl already in a redeclaration chain")(static_cast <bool> (RedeclLink.NextIsLatest() && "setPreviousDecl on a decl already in a redeclaration chain" ) ? void (0) : __assert_fail ("RedeclLink.NextIsLatest() && \"setPreviousDecl on a decl already in a redeclaration chain\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 4115, __extension__ __PRETTY_FUNCTION__)); |
4116 | |
4117 | if (PrevDecl) { |
4118 | // Point to previous. Make sure that this is actually the most recent |
4119 | // redeclaration, or we can build invalid chains. If the most recent |
4120 | // redeclaration is invalid, it won't be PrevDecl, but we want it anyway. |
4121 | First = PrevDecl->getFirstDecl(); |
4122 | assert(First->RedeclLink.NextIsLatest() && "Expected first")(static_cast <bool> (First->RedeclLink.NextIsLatest( ) && "Expected first") ? void (0) : __assert_fail ("First->RedeclLink.NextIsLatest() && \"Expected first\"" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 4122, __extension__ __PRETTY_FUNCTION__)); |
4123 | decl_type *MostRecent = First->getNextRedeclaration(); |
4124 | RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent)); |
4125 | |
4126 | // If the declaration was previously visible, a redeclaration of it remains |
4127 | // visible even if it wouldn't be visible by itself. |
4128 | static_cast<decl_type*>(this)->IdentifierNamespace |= |
4129 | MostRecent->getIdentifierNamespace() & |
4130 | (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type); |
4131 | } else { |
4132 | // Make this first. |
4133 | First = static_cast<decl_type*>(this); |
4134 | } |
4135 | |
4136 | // First one will point to this one as latest. |
4137 | First->RedeclLink.setLatest(static_cast<decl_type*>(this)); |
4138 | |
4139 | assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||(static_cast <bool> (!isa<NamedDecl>(static_cast< decl_type*>(this)) || cast<NamedDecl>(static_cast< decl_type*>(this))->isLinkageValid()) ? void (0) : __assert_fail ("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 4140, __extension__ __PRETTY_FUNCTION__)) |
4140 | cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid())(static_cast <bool> (!isa<NamedDecl>(static_cast< decl_type*>(this)) || cast<NamedDecl>(static_cast< decl_type*>(this))->isLinkageValid()) ? void (0) : __assert_fail ("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()" , "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/clang/include/clang/AST/Decl.h" , 4140, __extension__ __PRETTY_FUNCTION__)); |
4141 | } |
4142 | |
4143 | // Inline function definitions. |
4144 | |
4145 | /// \brief Check if the given decl is complete. |
4146 | /// |
4147 | /// We use this function to break a cycle between the inline definitions in |
4148 | /// Type.h and Decl.h. |
4149 | inline bool IsEnumDeclComplete(EnumDecl *ED) { |
4150 | return ED->isComplete(); |
4151 | } |
4152 | |
4153 | /// \brief Check if the given decl is scoped. |
4154 | /// |
4155 | /// We use this function to break a cycle between the inline definitions in |
4156 | /// Type.h and Decl.h. |
4157 | inline bool IsEnumDeclScoped(EnumDecl *ED) { |
4158 | return ED->isScoped(); |
4159 | } |
4160 | |
4161 | } // namespace clang |
4162 | |
4163 | #endif // LLVM_CLANG_AST_DECL_H |