1 //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This coordinates the per-function state used while generating code.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenFunction.h"
16 #include "CGCleanup.h"
17 #include "CGCUDARuntime.h"
19 #include "CGDebugInfo.h"
20 #include "CGOpenMPRuntime.h"
21 #include "CodeGenModule.h"
22 #include "CodeGenPGO.h"
23 #include "TargetInfo.h"
24 #include "clang/AST/ASTContext.h"
25 #include "clang/AST/Decl.h"
26 #include "clang/AST/DeclCXX.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/AST/StmtObjC.h"
29 #include "clang/Basic/Builtins.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/CodeGen/CGFunctionInfo.h"
32 #include "clang/Frontend/CodeGenOptions.h"
33 #include "clang/Sema/SemaDiagnostic.h"
34 #include "llvm/IR/DataLayout.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/IR/MDBuilder.h"
37 #include "llvm/IR/Operator.h"
38 using namespace clang;
39 using namespace CodeGen;
41 /// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
43 static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
44 const LangOptions &LangOpts) {
45 if (CGOpts.DisableLifetimeMarkers)
48 // Asan uses markers for use-after-scope checks.
49 if (CGOpts.SanitizeAddressUseAfterScope)
52 // Disable lifetime markers in msan builds.
53 // FIXME: Remove this when msan works with lifetime markers.
54 if (LangOpts.Sanitize.has(SanitizerKind::Memory))
57 // For now, only in optimized builds.
58 return CGOpts.OptimizationLevel != 0;
61 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
62 : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
63 Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
64 CGBuilderInserterTy(this)),
65 CurFn(nullptr), ReturnValue(Address::invalid()),
66 CapturedStmtInfo(nullptr), SanOpts(CGM.getLangOpts().Sanitize),
67 IsSanitizerScope(false), CurFuncIsThunk(false), AutoreleaseResult(false),
68 SawAsmBlock(false), IsOutlinedSEHHelper(false), BlockInfo(nullptr),
69 BlockPointer(nullptr), LambdaThisCaptureField(nullptr),
70 NormalCleanupDest(nullptr), NextCleanupDestIndex(1),
71 FirstBlockInfo(nullptr), EHResumeBlock(nullptr), ExceptionSlot(nullptr),
72 EHSelectorSlot(nullptr), DebugInfo(CGM.getModuleDebugInfo()),
73 DisableDebugInfo(false), DidCallStackSave(false), IndirectBranch(nullptr),
74 PGO(cgm), SwitchInsn(nullptr), SwitchWeights(nullptr),
75 CaseRangeBlock(nullptr), UnreachableBlock(nullptr), NumReturnExprs(0),
76 NumSimpleReturnExprs(0), CXXABIThisDecl(nullptr),
77 CXXABIThisValue(nullptr), CXXThisValue(nullptr),
78 CXXStructorImplicitParamDecl(nullptr),
79 CXXStructorImplicitParamValue(nullptr), OutermostConditional(nullptr),
80 CurLexicalScope(nullptr), TerminateLandingPad(nullptr),
81 TerminateHandler(nullptr), TrapBB(nullptr),
82 ShouldEmitLifetimeMarkers(
83 shouldEmitLifetimeMarkers(CGM.getCodeGenOpts(), CGM.getLangOpts())) {
84 if (!suppressNewContext)
85 CGM.getCXXABI().getMangleContext().startNewFunction();
87 llvm::FastMathFlags FMF;
88 if (CGM.getLangOpts().FastMath)
89 FMF.setUnsafeAlgebra();
90 if (CGM.getLangOpts().FiniteMathOnly) {
94 if (CGM.getCodeGenOpts().NoNaNsFPMath) {
97 if (CGM.getCodeGenOpts().NoSignedZeros) {
98 FMF.setNoSignedZeros();
100 if (CGM.getCodeGenOpts().ReciprocalMath) {
101 FMF.setAllowReciprocal();
103 Builder.setFastMathFlags(FMF);
106 CodeGenFunction::~CodeGenFunction() {
107 assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
109 // If there are any unclaimed block infos, go ahead and destroy them
110 // now. This can happen if IR-gen gets clever and skips evaluating
113 destroyBlockInfos(FirstBlockInfo);
115 if (getLangOpts().OpenMP) {
116 CGM.getOpenMPRuntime().functionFinished(*this);
120 CharUnits CodeGenFunction::getNaturalPointeeTypeAlignment(QualType T,
121 AlignmentSource *Source) {
122 return getNaturalTypeAlignment(T->getPointeeType(), Source,
123 /*forPointee*/ true);
126 CharUnits CodeGenFunction::getNaturalTypeAlignment(QualType T,
127 AlignmentSource *Source,
128 bool forPointeeType) {
129 // Honor alignment typedef attributes even on incomplete types.
130 // We also honor them straight for C++ class types, even as pointees;
131 // there's an expressivity gap here.
132 if (auto TT = T->getAs<TypedefType>()) {
133 if (auto Align = TT->getDecl()->getMaxAlignment()) {
134 if (Source) *Source = AlignmentSource::AttributedType;
135 return getContext().toCharUnitsFromBits(Align);
139 if (Source) *Source = AlignmentSource::Type;
142 if (T->isIncompleteType()) {
143 Alignment = CharUnits::One(); // Shouldn't be used, but pessimistic is best.
145 // For C++ class pointees, we don't know whether we're pointing at a
146 // base or a complete object, so we generally need to use the
147 // non-virtual alignment.
148 const CXXRecordDecl *RD;
149 if (forPointeeType && (RD = T->getAsCXXRecordDecl())) {
150 Alignment = CGM.getClassPointerAlignment(RD);
152 Alignment = getContext().getTypeAlignInChars(T);
155 // Cap to the global maximum type alignment unless the alignment
156 // was somehow explicit on the type.
157 if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
158 if (Alignment.getQuantity() > MaxAlign &&
159 !getContext().isAlignmentRequired(T))
160 Alignment = CharUnits::fromQuantity(MaxAlign);
166 LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
167 AlignmentSource AlignSource;
168 CharUnits Alignment = getNaturalTypeAlignment(T, &AlignSource);
169 return LValue::MakeAddr(Address(V, Alignment), T, getContext(), AlignSource,
173 /// Given a value of type T* that may not be to a complete object,
174 /// construct an l-value with the natural pointee alignment of T.
176 CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
177 AlignmentSource AlignSource;
178 CharUnits Align = getNaturalTypeAlignment(T, &AlignSource, /*pointee*/ true);
179 return MakeAddrLValue(Address(V, Align), T, AlignSource);
183 llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
184 return CGM.getTypes().ConvertTypeForMem(T);
187 llvm::Type *CodeGenFunction::ConvertType(QualType T) {
188 return CGM.getTypes().ConvertType(T);
191 TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
192 type = type.getCanonicalType();
194 switch (type->getTypeClass()) {
195 #define TYPE(name, parent)
196 #define ABSTRACT_TYPE(name, parent)
197 #define NON_CANONICAL_TYPE(name, parent) case Type::name:
198 #define DEPENDENT_TYPE(name, parent) case Type::name:
199 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
200 #include "clang/AST/TypeNodes.def"
201 llvm_unreachable("non-canonical or dependent type in IR-generation");
204 llvm_unreachable("undeduced auto type in IR-generation");
206 // Various scalar types.
209 case Type::BlockPointer:
210 case Type::LValueReference:
211 case Type::RValueReference:
212 case Type::MemberPointer:
214 case Type::ExtVector:
215 case Type::FunctionProto:
216 case Type::FunctionNoProto:
218 case Type::ObjCObjectPointer:
226 // Arrays, records, and Objective-C objects.
227 case Type::ConstantArray:
228 case Type::IncompleteArray:
229 case Type::VariableArray:
231 case Type::ObjCObject:
232 case Type::ObjCInterface:
233 return TEK_Aggregate;
235 // We operate on atomic values according to their underlying type.
237 type = cast<AtomicType>(type)->getValueType();
240 llvm_unreachable("unknown type kind!");
244 llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
245 // For cleanliness, we try to avoid emitting the return block for
247 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
250 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
252 // We have a valid insert point, reuse it if it is empty or there are no
253 // explicit jumps to the return block.
254 if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
255 ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
256 delete ReturnBlock.getBlock();
258 EmitBlock(ReturnBlock.getBlock());
259 return llvm::DebugLoc();
262 // Otherwise, if the return block is the target of a single direct
263 // branch then we can just put the code in that block instead. This
264 // cleans up functions which started with a unified return block.
265 if (ReturnBlock.getBlock()->hasOneUse()) {
266 llvm::BranchInst *BI =
267 dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
268 if (BI && BI->isUnconditional() &&
269 BI->getSuccessor(0) == ReturnBlock.getBlock()) {
270 // Record/return the DebugLoc of the simple 'return' expression to be used
271 // later by the actual 'ret' instruction.
272 llvm::DebugLoc Loc = BI->getDebugLoc();
273 Builder.SetInsertPoint(BI->getParent());
274 BI->eraseFromParent();
275 delete ReturnBlock.getBlock();
280 // FIXME: We are at an unreachable point, there is no reason to emit the block
281 // unless it has uses. However, we still need a place to put the debug
282 // region.end for now.
284 EmitBlock(ReturnBlock.getBlock());
285 return llvm::DebugLoc();
288 static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
290 if (!BB->use_empty())
291 return CGF.CurFn->getBasicBlockList().push_back(BB);
295 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
296 assert(BreakContinueStack.empty() &&
297 "mismatched push/pop in break/continue stack!");
299 bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
300 && NumSimpleReturnExprs == NumReturnExprs
301 && ReturnBlock.getBlock()->use_empty();
302 // Usually the return expression is evaluated before the cleanup
303 // code. If the function contains only a simple return statement,
304 // such as a constant, the location before the cleanup code becomes
305 // the last useful breakpoint in the function, because the simple
306 // return expression will be evaluated after the cleanup code. To be
307 // safe, set the debug location for cleanup code to the location of
308 // the return statement. Otherwise the cleanup code should be at the
309 // end of the function's lexical scope.
311 // If there are multiple branches to the return block, the branch
312 // instructions will get the location of the return statements and
314 if (CGDebugInfo *DI = getDebugInfo()) {
315 if (OnlySimpleReturnStmts)
316 DI->EmitLocation(Builder, LastStopPoint);
318 DI->EmitLocation(Builder, EndLoc);
321 // Pop any cleanups that might have been associated with the
322 // parameters. Do this in whatever block we're currently in; it's
323 // important to do this before we enter the return block or return
324 // edges will be *really* confused.
325 bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
326 bool HasOnlyLifetimeMarkers =
327 HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth);
328 bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
330 // Make sure the line table doesn't jump back into the body for
331 // the ret after it's been at EndLoc.
332 if (CGDebugInfo *DI = getDebugInfo())
333 if (OnlySimpleReturnStmts)
334 DI->EmitLocation(Builder, EndLoc);
336 PopCleanupBlocks(PrologueCleanupDepth);
339 // Emit function epilog (to return).
340 llvm::DebugLoc Loc = EmitReturnBlock();
342 if (ShouldInstrumentFunction())
343 EmitFunctionInstrumentation("__cyg_profile_func_exit");
345 // Emit debug descriptor for function end.
346 if (CGDebugInfo *DI = getDebugInfo())
347 DI->EmitFunctionEnd(Builder);
349 // Reset the debug location to that of the simple 'return' expression, if any
350 // rather than that of the end of the function's scope '}'.
351 ApplyDebugLocation AL(*this, Loc);
352 EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
353 EmitEndEHSpec(CurCodeDecl);
355 assert(EHStack.empty() &&
356 "did not remove all scopes from cleanup stack!");
358 // If someone did an indirect goto, emit the indirect goto block at the end of
360 if (IndirectBranch) {
361 EmitBlock(IndirectBranch->getParent());
362 Builder.ClearInsertionPoint();
365 // If some of our locals escaped, insert a call to llvm.localescape in the
367 if (!EscapedLocals.empty()) {
368 // Invert the map from local to index into a simple vector. There should be
370 SmallVector<llvm::Value *, 4> EscapeArgs;
371 EscapeArgs.resize(EscapedLocals.size());
372 for (auto &Pair : EscapedLocals)
373 EscapeArgs[Pair.second] = Pair.first;
374 llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
375 &CGM.getModule(), llvm::Intrinsic::localescape);
376 CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
379 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
380 llvm::Instruction *Ptr = AllocaInsertPt;
381 AllocaInsertPt = nullptr;
382 Ptr->eraseFromParent();
384 // If someone took the address of a label but never did an indirect goto, we
385 // made a zero entry PHI node, which is illegal, zap it now.
386 if (IndirectBranch) {
387 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
388 if (PN->getNumIncomingValues() == 0) {
389 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
390 PN->eraseFromParent();
394 EmitIfUsed(*this, EHResumeBlock);
395 EmitIfUsed(*this, TerminateLandingPad);
396 EmitIfUsed(*this, TerminateHandler);
397 EmitIfUsed(*this, UnreachableBlock);
399 if (CGM.getCodeGenOpts().EmitDeclMetadata)
402 for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
403 I = DeferredReplacements.begin(),
404 E = DeferredReplacements.end();
406 I->first->replaceAllUsesWith(I->second);
407 I->first->eraseFromParent();
411 /// ShouldInstrumentFunction - Return true if the current function should be
412 /// instrumented with __cyg_profile_func_* calls
413 bool CodeGenFunction::ShouldInstrumentFunction() {
414 if (!CGM.getCodeGenOpts().InstrumentFunctions)
416 if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
421 /// ShouldXRayInstrument - Return true if the current function should be
422 /// instrumented with XRay nop sleds.
423 bool CodeGenFunction::ShouldXRayInstrumentFunction() const {
424 return CGM.getCodeGenOpts().XRayInstrumentFunctions;
427 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
428 /// instrumentation function with the current function and the call site, if
429 /// function instrumentation is enabled.
430 void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
431 auto NL = ApplyDebugLocation::CreateArtificial(*this);
432 // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
433 llvm::PointerType *PointerTy = Int8PtrTy;
434 llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy };
435 llvm::FunctionType *FunctionTy =
436 llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false);
438 llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
439 llvm::CallInst *CallSite = Builder.CreateCall(
440 CGM.getIntrinsic(llvm::Intrinsic::returnaddress),
441 llvm::ConstantInt::get(Int32Ty, 0),
444 llvm::Value *args[] = {
445 llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
449 EmitNounwindRuntimeCall(F, args);
452 static void removeImageAccessQualifier(std::string& TyName) {
453 std::string ReadOnlyQual("__read_only");
454 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
455 if (ReadOnlyPos != std::string::npos)
456 // "+ 1" for the space after access qualifier.
457 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
459 std::string WriteOnlyQual("__write_only");
460 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
461 if (WriteOnlyPos != std::string::npos)
462 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
464 std::string ReadWriteQual("__read_write");
465 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
466 if (ReadWritePos != std::string::npos)
467 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
472 // Returns the address space id that should be produced to the
473 // kernel_arg_addr_space metadata. This is always fixed to the ids
474 // as specified in the SPIR 2.0 specification in order to differentiate
475 // for example in clGetKernelArgInfo() implementation between the address
476 // spaces with targets without unique mapping to the OpenCL address spaces
477 // (basically all single AS CPUs).
478 static unsigned ArgInfoAddressSpace(unsigned LangAS) {
480 case LangAS::opencl_global: return 1;
481 case LangAS::opencl_constant: return 2;
482 case LangAS::opencl_local: return 3;
483 case LangAS::opencl_generic: return 4; // Not in SPIR 2.0 specs.
485 return 0; // Assume private.
489 // OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
490 // information in the program executable. The argument information stored
491 // includes the argument name, its type, the address and access qualifiers used.
492 static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn,
493 CodeGenModule &CGM, llvm::LLVMContext &Context,
494 CGBuilderTy &Builder, ASTContext &ASTCtx) {
495 // Create MDNodes that represent the kernel arg metadata.
496 // Each MDNode is a list in the form of "key", N number of values which is
497 // the same number of values as their are kernel arguments.
499 const PrintingPolicy &Policy = ASTCtx.getPrintingPolicy();
501 // MDNode for the kernel argument address space qualifiers.
502 SmallVector<llvm::Metadata *, 8> addressQuals;
504 // MDNode for the kernel argument access qualifiers (images only).
505 SmallVector<llvm::Metadata *, 8> accessQuals;
507 // MDNode for the kernel argument type names.
508 SmallVector<llvm::Metadata *, 8> argTypeNames;
510 // MDNode for the kernel argument base type names.
511 SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
513 // MDNode for the kernel argument type qualifiers.
514 SmallVector<llvm::Metadata *, 8> argTypeQuals;
516 // MDNode for the kernel argument names.
517 SmallVector<llvm::Metadata *, 8> argNames;
519 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
520 const ParmVarDecl *parm = FD->getParamDecl(i);
521 QualType ty = parm->getType();
522 std::string typeQuals;
524 if (ty->isPointerType()) {
525 QualType pointeeTy = ty->getPointeeType();
527 // Get address qualifier.
528 addressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(
529 ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
531 // Get argument type name.
532 std::string typeName =
533 pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
535 // Turn "unsigned type" to "utype"
536 std::string::size_type pos = typeName.find("unsigned");
537 if (pointeeTy.isCanonical() && pos != std::string::npos)
538 typeName.erase(pos+1, 8);
540 argTypeNames.push_back(llvm::MDString::get(Context, typeName));
542 std::string baseTypeName =
543 pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
547 // Turn "unsigned type" to "utype"
548 pos = baseTypeName.find("unsigned");
549 if (pos != std::string::npos)
550 baseTypeName.erase(pos+1, 8);
552 argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
554 // Get argument type qualifiers:
555 if (ty.isRestrictQualified())
556 typeQuals = "restrict";
557 if (pointeeTy.isConstQualified() ||
558 (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
559 typeQuals += typeQuals.empty() ? "const" : " const";
560 if (pointeeTy.isVolatileQualified())
561 typeQuals += typeQuals.empty() ? "volatile" : " volatile";
563 uint32_t AddrSpc = 0;
564 bool isPipe = ty->isPipeType();
565 if (ty->isImageType() || isPipe)
566 AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
568 addressQuals.push_back(
569 llvm::ConstantAsMetadata::get(Builder.getInt32(AddrSpc)));
571 // Get argument type name.
572 std::string typeName;
574 typeName = ty.getCanonicalType()->getAs<PipeType>()->getElementType()
575 .getAsString(Policy);
577 typeName = ty.getUnqualifiedType().getAsString(Policy);
579 // Turn "unsigned type" to "utype"
580 std::string::size_type pos = typeName.find("unsigned");
581 if (ty.isCanonical() && pos != std::string::npos)
582 typeName.erase(pos+1, 8);
584 std::string baseTypeName;
586 baseTypeName = ty.getCanonicalType()->getAs<PipeType>()
587 ->getElementType().getCanonicalType()
588 .getAsString(Policy);
591 ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
593 // Remove access qualifiers on images
594 // (as they are inseparable from type in clang implementation,
595 // but OpenCL spec provides a special query to get access qualifier
596 // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
597 if (ty->isImageType()) {
598 removeImageAccessQualifier(typeName);
599 removeImageAccessQualifier(baseTypeName);
602 argTypeNames.push_back(llvm::MDString::get(Context, typeName));
604 // Turn "unsigned type" to "utype"
605 pos = baseTypeName.find("unsigned");
606 if (pos != std::string::npos)
607 baseTypeName.erase(pos+1, 8);
609 argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
611 // Get argument type qualifiers:
612 if (ty.isConstQualified())
614 if (ty.isVolatileQualified())
615 typeQuals += typeQuals.empty() ? "volatile" : " volatile";
620 argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals));
622 // Get image and pipe access qualifier:
623 if (ty->isImageType()|| ty->isPipeType()) {
624 const OpenCLAccessAttr *A = parm->getAttr<OpenCLAccessAttr>();
625 if (A && A->isWriteOnly())
626 accessQuals.push_back(llvm::MDString::get(Context, "write_only"));
627 else if (A && A->isReadWrite())
628 accessQuals.push_back(llvm::MDString::get(Context, "read_write"));
630 accessQuals.push_back(llvm::MDString::get(Context, "read_only"));
632 accessQuals.push_back(llvm::MDString::get(Context, "none"));
634 // Get argument name.
635 argNames.push_back(llvm::MDString::get(Context, parm->getName()));
638 Fn->setMetadata("kernel_arg_addr_space",
639 llvm::MDNode::get(Context, addressQuals));
640 Fn->setMetadata("kernel_arg_access_qual",
641 llvm::MDNode::get(Context, accessQuals));
642 Fn->setMetadata("kernel_arg_type",
643 llvm::MDNode::get(Context, argTypeNames));
644 Fn->setMetadata("kernel_arg_base_type",
645 llvm::MDNode::get(Context, argBaseTypeNames));
646 Fn->setMetadata("kernel_arg_type_qual",
647 llvm::MDNode::get(Context, argTypeQuals));
648 if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
649 Fn->setMetadata("kernel_arg_name",
650 llvm::MDNode::get(Context, argNames));
653 void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
656 if (!FD->hasAttr<OpenCLKernelAttr>())
659 llvm::LLVMContext &Context = getLLVMContext();
661 GenOpenCLArgMetadata(FD, Fn, CGM, Context, Builder, getContext());
663 if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
664 QualType hintQTy = A->getTypeHint();
665 const ExtVectorType *hintEltQTy = hintQTy->getAs<ExtVectorType>();
666 bool isSignedInteger =
667 hintQTy->isSignedIntegerType() ||
668 (hintEltQTy && hintEltQTy->getElementType()->isSignedIntegerType());
669 llvm::Metadata *attrMDArgs[] = {
670 llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
671 CGM.getTypes().ConvertType(A->getTypeHint()))),
672 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
673 llvm::IntegerType::get(Context, 32),
674 llvm::APInt(32, (uint64_t)(isSignedInteger ? 1 : 0))))};
675 Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, attrMDArgs));
678 if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
679 llvm::Metadata *attrMDArgs[] = {
680 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
681 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
682 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
683 Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, attrMDArgs));
686 if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
687 llvm::Metadata *attrMDArgs[] = {
688 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
689 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
690 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
691 Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, attrMDArgs));
695 /// Determine whether the function F ends with a return stmt.
696 static bool endsWithReturn(const Decl* F) {
697 const Stmt *Body = nullptr;
698 if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
699 Body = FD->getBody();
700 else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
701 Body = OMD->getBody();
703 if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
704 auto LastStmt = CS->body_rbegin();
705 if (LastStmt != CS->body_rend())
706 return isa<ReturnStmt>(*LastStmt);
711 void CodeGenFunction::StartFunction(GlobalDecl GD,
714 const CGFunctionInfo &FnInfo,
715 const FunctionArgList &Args,
717 SourceLocation StartLoc) {
719 "Do not use a CodeGenFunction object for more than one function");
721 const Decl *D = GD.getDecl();
723 DidCallStackSave = false;
725 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D))
726 if (FD->usesSEHTry())
728 CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
732 assert(CurFn->isDeclaration() && "Function already has body?");
734 if (CGM.isInSanitizerBlacklist(Fn, Loc))
738 // Apply the no_sanitize* attributes to SanOpts.
739 for (auto Attr : D->specific_attrs<NoSanitizeAttr>())
740 SanOpts.Mask &= ~Attr->getMask();
743 // Apply sanitizer attributes to the function.
744 if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
745 Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
746 if (SanOpts.has(SanitizerKind::Thread))
747 Fn->addFnAttr(llvm::Attribute::SanitizeThread);
748 if (SanOpts.has(SanitizerKind::Memory))
749 Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
750 if (SanOpts.has(SanitizerKind::SafeStack))
751 Fn->addFnAttr(llvm::Attribute::SafeStack);
753 // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize,
754 // .cxx_destruct and all of their calees at run time.
755 if (SanOpts.has(SanitizerKind::Thread)) {
756 if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
757 IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
758 if (OMD->getMethodFamily() == OMF_dealloc ||
759 OMD->getMethodFamily() == OMF_initialize ||
760 (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) {
761 Fn->addFnAttr("sanitize_thread_no_checking_at_run_time");
762 Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
767 // Apply xray attributes to the function (as a string, for now)
768 if (D && ShouldXRayInstrumentFunction()) {
769 if (const auto *XRayAttr = D->getAttr<XRayInstrumentAttr>()) {
770 if (XRayAttr->alwaysXRayInstrument())
771 Fn->addFnAttr("function-instrument", "xray-always");
772 if (XRayAttr->neverXRayInstrument())
773 Fn->addFnAttr("function-instrument", "xray-never");
776 "xray-instruction-threshold",
777 llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
781 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
782 if (CGM.getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
783 CGM.getOpenMPRuntime().emitDeclareSimdFunction(FD, Fn);
785 // Add no-jump-tables value.
786 Fn->addFnAttr("no-jump-tables",
787 llvm::toStringRef(CGM.getCodeGenOpts().NoUseJumpTables));
789 if (getLangOpts().OpenCL) {
790 // Add metadata for a kernel function.
791 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
792 EmitOpenCLKernelMetadata(FD, Fn);
795 // If we are checking function types, emit a function type signature as
797 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
798 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
799 if (llvm::Constant *PrologueSig =
800 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
801 llvm::Constant *FTRTTIConst =
802 CGM.GetAddrOfRTTIDescriptor(FD->getType(), /*ForEH=*/true);
803 llvm::Constant *PrologueStructElems[] = { PrologueSig, FTRTTIConst };
804 llvm::Constant *PrologueStructConst =
805 llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
806 Fn->setPrologueData(PrologueStructConst);
811 // If we're in C++ mode and the function name is "main", it is guaranteed
812 // to be norecurse by the standard (3.6.1.3 "The function main shall not be
813 // used within a program").
814 if (getLangOpts().CPlusPlus)
815 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
817 Fn->addFnAttr(llvm::Attribute::NoRecurse);
819 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
821 // Create a marker to make it easy to insert allocas into the entryblock
822 // later. Don't create this with the builder, because we don't want it
824 llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
825 AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB);
827 ReturnBlock = getJumpDestInCurrentScope("return");
829 Builder.SetInsertPoint(EntryBB);
831 // Emit subprogram debug descriptor.
832 if (CGDebugInfo *DI = getDebugInfo()) {
833 // Reconstruct the type from the argument list so that implicit parameters,
834 // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
836 CallingConv CC = CallingConv::CC_C;
837 if (auto *FD = dyn_cast_or_null<FunctionDecl>(D))
838 if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
839 CC = SrcFnTy->getCallConv();
840 SmallVector<QualType, 16> ArgTypes;
841 for (const VarDecl *VD : Args)
842 ArgTypes.push_back(VD->getType());
843 QualType FnType = getContext().getFunctionType(
844 RetTy, ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
845 DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, Builder);
848 if (ShouldInstrumentFunction())
849 EmitFunctionInstrumentation("__cyg_profile_func_enter");
851 // Since emitting the mcount call here impacts optimizations such as function
852 // inlining, we just add an attribute to insert a mcount call in backend.
853 // The attribute "counting-function" is set to mcount function name which is
854 // architecture dependent.
855 if (CGM.getCodeGenOpts().InstrumentForProfiling)
856 Fn->addFnAttr("counting-function", getTarget().getMCountName());
858 if (RetTy->isVoidType()) {
859 // Void type; nothing to return.
860 ReturnValue = Address::invalid();
862 // Count the implicit return.
863 if (!endsWithReturn(D))
865 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
866 !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
867 // Indirect aggregate return; emit returned value directly into sret slot.
868 // This reduces code size, and affects correctness in C++.
869 auto AI = CurFn->arg_begin();
870 if (CurFnInfo->getReturnInfo().isSRetAfterThis())
872 ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign());
873 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
874 !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
875 // Load the sret pointer from the argument struct and return into that.
876 unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
877 llvm::Function::arg_iterator EI = CurFn->arg_end();
879 llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx);
880 Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result");
881 ReturnValue = Address(Addr, getNaturalTypeAlignment(RetTy));
883 ReturnValue = CreateIRTemp(RetTy, "retval");
885 // Tell the epilog emitter to autorelease the result. We do this
886 // now so that various specialized functions can suppress it
887 // during their IR-generation.
888 if (getLangOpts().ObjCAutoRefCount &&
889 !CurFnInfo->isReturnsRetained() &&
890 RetTy->isObjCRetainableType())
891 AutoreleaseResult = true;
894 EmitStartEHSpec(CurCodeDecl);
896 PrologueCleanupDepth = EHStack.stable_begin();
897 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
899 if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
900 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
901 const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
902 if (MD->getParent()->isLambda() &&
903 MD->getOverloadedOperator() == OO_Call) {
904 // We're in a lambda; figure out the captures.
905 MD->getParent()->getCaptureFields(LambdaCaptureFields,
906 LambdaThisCaptureField);
907 if (LambdaThisCaptureField) {
908 // If the lambda captures the object referred to by '*this' - either by
909 // value or by reference, make sure CXXThisValue points to the correct
912 // Get the lvalue for the field (which is a copy of the enclosing object
913 // or contains the address of the enclosing object).
914 LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
915 if (!LambdaThisCaptureField->getType()->isPointerType()) {
916 // If the enclosing object was captured by value, just use its address.
917 CXXThisValue = ThisFieldLValue.getAddress().getPointer();
919 // Load the lvalue pointed to by the field, since '*this' was captured
922 EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
925 for (auto *FD : MD->getParent()->fields()) {
926 if (FD->hasCapturedVLAType()) {
927 auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
928 SourceLocation()).getScalarVal();
929 auto VAT = FD->getCapturedVLAType();
930 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
934 // Not in a lambda; just use 'this' from the method.
935 // FIXME: Should we generate a new load for each use of 'this'? The
936 // fast register allocator would be happier...
937 CXXThisValue = CXXABIThisValue;
941 // If any of the arguments have a variably modified type, make sure to
942 // emit the type size.
943 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
945 const VarDecl *VD = *i;
947 // Dig out the type as written from ParmVarDecls; it's unclear whether
948 // the standard (C99 6.9.1p10) requires this, but we're following the
949 // precedent set by gcc.
951 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
952 Ty = PVD->getOriginalType();
956 if (Ty->isVariablyModifiedType())
957 EmitVariablyModifiedType(Ty);
959 // Emit a location at the end of the prologue.
960 if (CGDebugInfo *DI = getDebugInfo())
961 DI->EmitLocation(Builder, StartLoc);
964 void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args,
966 incrementProfileCounter(Body);
967 if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
968 EmitCompoundStmtWithoutScope(*S);
973 /// When instrumenting to collect profile data, the counts for some blocks
974 /// such as switch cases need to not include the fall-through counts, so
975 /// emit a branch around the instrumentation code. When not instrumenting,
976 /// this just calls EmitBlock().
977 void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
979 llvm::BasicBlock *SkipCountBB = nullptr;
980 if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) {
981 // When instrumenting for profiling, the fallthrough to certain
982 // statements needs to skip over the instrumentation code so that we
983 // get an accurate count.
984 SkipCountBB = createBasicBlock("skipcount");
985 EmitBranch(SkipCountBB);
988 uint64_t CurrentCount = getCurrentProfileCount();
989 incrementProfileCounter(S);
990 setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
992 EmitBlock(SkipCountBB);
995 /// Tries to mark the given function nounwind based on the
996 /// non-existence of any throwing calls within it. We believe this is
997 /// lightweight enough to do at -O0.
998 static void TryMarkNoThrow(llvm::Function *F) {
999 // LLVM treats 'nounwind' on a function as part of the type, so we
1000 // can't do this on functions that can be overwritten.
1001 if (F->isInterposable()) return;
1003 for (llvm::BasicBlock &BB : *F)
1004 for (llvm::Instruction &I : BB)
1008 F->setDoesNotThrow();
1011 QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
1012 FunctionArgList &Args) {
1013 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1014 QualType ResTy = FD->getReturnType();
1016 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1017 if (MD && MD->isInstance()) {
1018 if (CGM.getCXXABI().HasThisReturn(GD))
1019 ResTy = MD->getThisType(getContext());
1020 else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
1021 ResTy = CGM.getContext().VoidPtrTy;
1022 CGM.getCXXABI().buildThisParam(*this, Args);
1025 // The base version of an inheriting constructor whose constructed base is a
1026 // virtual base is not passed any arguments (because it doesn't actually call
1027 // the inherited constructor).
1028 bool PassedParams = true;
1029 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
1030 if (auto Inherited = CD->getInheritedConstructor())
1032 getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
1035 for (auto *Param : FD->parameters()) {
1036 Args.push_back(Param);
1037 if (!Param->hasAttr<PassObjectSizeAttr>())
1040 IdentifierInfo *NoID = nullptr;
1041 auto *Implicit = ImplicitParamDecl::Create(
1042 getContext(), Param->getDeclContext(), Param->getLocation(), NoID,
1043 getContext().getSizeType());
1044 SizeArguments[Param] = Implicit;
1045 Args.push_back(Implicit);
1049 if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
1050 CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
1056 shouldUseUndefinedBehaviorReturnOptimization(const FunctionDecl *FD,
1057 const ASTContext &Context) {
1058 QualType T = FD->getReturnType();
1059 // Avoid the optimization for functions that return a record type with a
1060 // trivial destructor or another trivially copyable type.
1061 if (const RecordType *RT = T.getCanonicalType()->getAs<RecordType>()) {
1062 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1063 return !ClassDecl->hasTrivialDestructor();
1065 return !T.isTriviallyCopyableType(Context);
1068 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1069 const CGFunctionInfo &FnInfo) {
1070 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1073 FunctionArgList Args;
1074 QualType ResTy = BuildFunctionArgList(GD, Args);
1076 // Check if we should generate debug info for this function.
1077 if (FD->hasAttr<NoDebugAttr>())
1078 DebugInfo = nullptr; // disable debug info indefinitely for this function
1080 SourceRange BodyRange;
1081 if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
1082 CurEHLocation = BodyRange.getEnd();
1084 // Use the location of the start of the function to determine where
1085 // the function definition is located. By default use the location
1086 // of the declaration as the location for the subprogram. A function
1087 // may lack a declaration in the source code if it is created by code
1088 // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
1089 SourceLocation Loc = FD->getLocation();
1091 // If this is a function specialization then use the pattern body
1092 // as the location for the function.
1093 if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
1094 if (SpecDecl->hasBody(SpecDecl))
1095 Loc = SpecDecl->getLocation();
1097 Stmt *Body = FD->getBody();
1099 // Initialize helper which will detect jumps which can cause invalid lifetime
1101 if (Body && ShouldEmitLifetimeMarkers)
1102 Bypasses.Init(Body);
1104 // Emit the standard function prologue.
1105 StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
1107 // Generate the body of the function.
1108 PGO.assignRegionCounters(GD, CurFn);
1109 if (isa<CXXDestructorDecl>(FD))
1110 EmitDestructorBody(Args);
1111 else if (isa<CXXConstructorDecl>(FD))
1112 EmitConstructorBody(Args);
1113 else if (getLangOpts().CUDA &&
1114 !getLangOpts().CUDAIsDevice &&
1115 FD->hasAttr<CUDAGlobalAttr>())
1116 CGM.getCUDARuntime().emitDeviceStub(*this, Args);
1117 else if (isa<CXXConversionDecl>(FD) &&
1118 cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) {
1119 // The lambda conversion to block pointer is special; the semantics can't be
1120 // expressed in the AST, so IRGen needs to special-case it.
1121 EmitLambdaToBlockPointerBody(Args);
1122 } else if (isa<CXXMethodDecl>(FD) &&
1123 cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
1124 // The lambda static invoker function is special, because it forwards or
1125 // clones the body of the function call operator (but is actually static).
1126 EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD));
1127 } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
1128 (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
1129 cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
1130 // Implicit copy-assignment gets the same special treatment as implicit
1131 // copy-constructors.
1132 emitImplicitAssignmentOperatorBody(Args);
1134 EmitFunctionBody(Args, Body);
1136 llvm_unreachable("no definition for emitted function");
1138 // C++11 [stmt.return]p2:
1139 // Flowing off the end of a function [...] results in undefined behavior in
1140 // a value-returning function.
1142 // If the '}' that terminates a function is reached, and the value of the
1143 // function call is used by the caller, the behavior is undefined.
1144 if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
1145 !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
1146 bool ShouldEmitUnreachable =
1147 CGM.getCodeGenOpts().StrictReturn ||
1148 shouldUseUndefinedBehaviorReturnOptimization(FD, getContext());
1149 if (SanOpts.has(SanitizerKind::Return)) {
1150 SanitizerScope SanScope(this);
1151 llvm::Value *IsFalse = Builder.getFalse();
1152 EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
1153 SanitizerHandler::MissingReturn,
1154 EmitCheckSourceLocation(FD->getLocation()), None);
1155 } else if (ShouldEmitUnreachable) {
1156 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
1157 EmitTrapCall(llvm::Intrinsic::trap);
1159 if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) {
1160 Builder.CreateUnreachable();
1161 Builder.ClearInsertionPoint();
1165 // Emit the standard function epilogue.
1166 FinishFunction(BodyRange.getEnd());
1168 // If we haven't marked the function nothrow through other means, do
1169 // a quick pass now to see if we can.
1170 if (!CurFn->doesNotThrow())
1171 TryMarkNoThrow(CurFn);
1174 /// ContainsLabel - Return true if the statement contains a label in it. If
1175 /// this statement is not executed normally, it not containing a label means
1176 /// that we can just remove the code.
1177 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
1178 // Null statement, not a label!
1179 if (!S) return false;
1181 // If this is a label, we have to emit the code, consider something like:
1182 // if (0) { ... foo: bar(); } goto foo;
1184 // TODO: If anyone cared, we could track __label__'s, since we know that you
1185 // can't jump to one from outside their declared region.
1186 if (isa<LabelStmt>(S))
1189 // If this is a case/default statement, and we haven't seen a switch, we have
1190 // to emit the code.
1191 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
1194 // If this is a switch statement, we want to ignore cases below it.
1195 if (isa<SwitchStmt>(S))
1196 IgnoreCaseStmts = true;
1198 // Scan subexpressions for verboten labels.
1199 for (const Stmt *SubStmt : S->children())
1200 if (ContainsLabel(SubStmt, IgnoreCaseStmts))
1206 /// containsBreak - Return true if the statement contains a break out of it.
1207 /// If the statement (recursively) contains a switch or loop with a break
1208 /// inside of it, this is fine.
1209 bool CodeGenFunction::containsBreak(const Stmt *S) {
1210 // Null statement, not a label!
1211 if (!S) return false;
1213 // If this is a switch or loop that defines its own break scope, then we can
1214 // include it and anything inside of it.
1215 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
1219 if (isa<BreakStmt>(S))
1222 // Scan subexpressions for verboten breaks.
1223 for (const Stmt *SubStmt : S->children())
1224 if (containsBreak(SubStmt))
1230 bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) {
1231 if (!S) return false;
1233 // Some statement kinds add a scope and thus never add a decl to the current
1234 // scope. Note, this list is longer than the list of statements that might
1235 // have an unscoped decl nested within them, but this way is conservatively
1236 // correct even if more statement kinds are added.
1237 if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1238 isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) ||
1239 isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) ||
1240 isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S))
1243 if (isa<DeclStmt>(S))
1246 for (const Stmt *SubStmt : S->children())
1247 if (mightAddDeclToScope(SubStmt))
1253 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1254 /// to a constant, or if it does but contains a label, return false. If it
1255 /// constant folds return true and set the boolean result in Result.
1256 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1259 llvm::APSInt ResultInt;
1260 if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
1263 ResultBool = ResultInt.getBoolValue();
1267 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1268 /// to a constant, or if it does but contains a label, return false. If it
1269 /// constant folds return true and set the folded value.
1270 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1271 llvm::APSInt &ResultInt,
1273 // FIXME: Rename and handle conversion of other evaluatable things
1276 if (!Cond->EvaluateAsInt(Int, getContext()))
1277 return false; // Not foldable, not integer or not fully evaluatable.
1279 if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
1280 return false; // Contains a label.
1288 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1289 /// statement) to the specified blocks. Based on the condition, this might try
1290 /// to simplify the codegen of the conditional based on the branch.
1292 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
1293 llvm::BasicBlock *TrueBlock,
1294 llvm::BasicBlock *FalseBlock,
1295 uint64_t TrueCount) {
1296 Cond = Cond->IgnoreParens();
1298 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
1300 // Handle X && Y in a condition.
1301 if (CondBOp->getOpcode() == BO_LAnd) {
1302 // If we have "1 && X", simplify the code. "0 && X" would have constant
1303 // folded if the case was simple enough.
1304 bool ConstantBool = false;
1305 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1307 // br(1 && X) -> br(X).
1308 incrementProfileCounter(CondBOp);
1309 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
1313 // If we have "X && 1", simplify the code to use an uncond branch.
1314 // "X && 0" would have been constant folded to 0.
1315 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1317 // br(X && 1) -> br(X).
1318 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
1322 // Emit the LHS as a conditional. If the LHS conditional is false, we
1323 // want to jump to the FalseBlock.
1324 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
1325 // The counter tells us how often we evaluate RHS, and all of TrueCount
1326 // can be propagated to that branch.
1327 uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
1329 ConditionalEvaluation eval(*this);
1331 ApplyDebugLocation DL(*this, Cond);
1332 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
1336 incrementProfileCounter(CondBOp);
1337 setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1339 // Any temporaries created here are conditional.
1341 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount);
1347 if (CondBOp->getOpcode() == BO_LOr) {
1348 // If we have "0 || X", simplify the code. "1 || X" would have constant
1349 // folded if the case was simple enough.
1350 bool ConstantBool = false;
1351 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1353 // br(0 || X) -> br(X).
1354 incrementProfileCounter(CondBOp);
1355 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
1359 // If we have "X || 0", simplify the code to use an uncond branch.
1360 // "X || 1" would have been constant folded to 1.
1361 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1363 // br(X || 0) -> br(X).
1364 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
1368 // Emit the LHS as a conditional. If the LHS conditional is true, we
1369 // want to jump to the TrueBlock.
1370 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
1371 // We have the count for entry to the RHS and for the whole expression
1372 // being true, so we can divy up True count between the short circuit and
1375 getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
1376 uint64_t RHSCount = TrueCount - LHSCount;
1378 ConditionalEvaluation eval(*this);
1380 ApplyDebugLocation DL(*this, Cond);
1381 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
1382 EmitBlock(LHSFalse);
1385 incrementProfileCounter(CondBOp);
1386 setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1388 // Any temporaries created here are conditional.
1390 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount);
1398 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1399 // br(!x, t, f) -> br(x, f, t)
1400 if (CondUOp->getOpcode() == UO_LNot) {
1401 // Negate the count.
1402 uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
1403 // Negate the condition and swap the destination blocks.
1404 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
1409 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
1410 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
1411 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
1412 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
1414 ConditionalEvaluation cond(*this);
1415 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
1416 getProfileCount(CondOp));
1418 // When computing PGO branch weights, we only know the overall count for
1419 // the true block. This code is essentially doing tail duplication of the
1420 // naive code-gen, introducing new edges for which counts are not
1421 // available. Divide the counts proportionally between the LHS and RHS of
1422 // the conditional operator.
1423 uint64_t LHSScaledTrueCount = 0;
1426 getProfileCount(CondOp) / (double)getCurrentProfileCount();
1427 LHSScaledTrueCount = TrueCount * LHSRatio;
1431 EmitBlock(LHSBlock);
1432 incrementProfileCounter(CondOp);
1434 ApplyDebugLocation DL(*this, Cond);
1435 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
1436 LHSScaledTrueCount);
1441 EmitBlock(RHSBlock);
1442 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
1443 TrueCount - LHSScaledTrueCount);
1449 if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
1450 // Conditional operator handling can give us a throw expression as a
1451 // condition for a case like:
1452 // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
1454 // br(c, throw x, br(y, t, f))
1455 EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
1459 // If the branch has a condition wrapped by __builtin_unpredictable,
1460 // create metadata that specifies that the branch is unpredictable.
1461 // Don't bother if not optimizing because that metadata would not be used.
1462 llvm::MDNode *Unpredictable = nullptr;
1463 auto *Call = dyn_cast<CallExpr>(Cond);
1464 if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
1465 auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
1466 if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
1467 llvm::MDBuilder MDHelper(getLLVMContext());
1468 Unpredictable = MDHelper.createUnpredictable();
1472 // Create branch weights based on the number of times we get here and the
1473 // number of times the condition should be true.
1474 uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
1475 llvm::MDNode *Weights =
1476 createProfileWeights(TrueCount, CurrentCount - TrueCount);
1478 // Emit the code with the fully general case.
1481 ApplyDebugLocation DL(*this, Cond);
1482 CondV = EvaluateExprAsBool(Cond);
1484 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
1487 /// ErrorUnsupported - Print out an error that codegen doesn't support the
1488 /// specified stmt yet.
1489 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
1490 CGM.ErrorUnsupported(S, Type);
1493 /// emitNonZeroVLAInit - Emit the "zero" initialization of a
1494 /// variable-length array whose elements have a non-zero bit-pattern.
1496 /// \param baseType the inner-most element type of the array
1497 /// \param src - a char* pointing to the bit-pattern for a single
1498 /// base element of the array
1499 /// \param sizeInChars - the total size of the VLA, in chars
1500 static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
1501 Address dest, Address src,
1502 llvm::Value *sizeInChars) {
1503 CGBuilderTy &Builder = CGF.Builder;
1505 CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
1506 llvm::Value *baseSizeInChars
1507 = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
1510 Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin");
1512 Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars, "vla.end");
1514 llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
1515 llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
1516 llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
1518 // Make a loop over the VLA. C99 guarantees that the VLA element
1519 // count must be nonzero.
1520 CGF.EmitBlock(loopBB);
1522 llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
1523 cur->addIncoming(begin.getPointer(), originBB);
1525 CharUnits curAlign =
1526 dest.getAlignment().alignmentOfArrayElement(baseSize);
1528 // memcpy the individual element bit-pattern.
1529 Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars,
1530 /*volatile*/ false);
1532 // Go to the next element.
1534 Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
1536 // Leave if that's the end of the VLA.
1537 llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
1538 Builder.CreateCondBr(done, contBB, loopBB);
1539 cur->addIncoming(next, loopBB);
1541 CGF.EmitBlock(contBB);
1545 CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
1546 // Ignore empty classes in C++.
1547 if (getLangOpts().CPlusPlus) {
1548 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1549 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
1554 // Cast the dest ptr to the appropriate i8 pointer type.
1555 if (DestPtr.getElementType() != Int8Ty)
1556 DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
1558 // Get size and alignment info for this aggregate.
1559 CharUnits size = getContext().getTypeSizeInChars(Ty);
1561 llvm::Value *SizeVal;
1562 const VariableArrayType *vla;
1564 // Don't bother emitting a zero-byte memset.
1565 if (size.isZero()) {
1566 // But note that getTypeInfo returns 0 for a VLA.
1567 if (const VariableArrayType *vlaType =
1568 dyn_cast_or_null<VariableArrayType>(
1569 getContext().getAsArrayType(Ty))) {
1571 llvm::Value *numElts;
1572 std::tie(numElts, eltType) = getVLASize(vlaType);
1575 CharUnits eltSize = getContext().getTypeSizeInChars(eltType);
1576 if (!eltSize.isOne())
1577 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
1583 SizeVal = CGM.getSize(size);
1587 // If the type contains a pointer to data member we can't memset it to zero.
1588 // Instead, create a null constant and copy it to the destination.
1589 // TODO: there are other patterns besides zero that we can usefully memset,
1590 // like -1, which happens to be the pattern used by member-pointers.
1591 if (!CGM.getTypes().isZeroInitializable(Ty)) {
1592 // For a VLA, emit a single element, then splat that over the VLA.
1593 if (vla) Ty = getContext().getBaseElementType(vla);
1595 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
1597 llvm::GlobalVariable *NullVariable =
1598 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
1599 /*isConstant=*/true,
1600 llvm::GlobalVariable::PrivateLinkage,
1601 NullConstant, Twine());
1602 CharUnits NullAlign = DestPtr.getAlignment();
1603 NullVariable->setAlignment(NullAlign.getQuantity());
1604 Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()),
1607 if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
1609 // Get and call the appropriate llvm.memcpy overload.
1610 Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
1614 // Otherwise, just memset the whole thing to zero. This is legal
1615 // because in LLVM, all default initializers (other than the ones we just
1616 // handled above) are guaranteed to have a bit pattern of all zeros.
1617 Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
1620 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
1621 // Make sure that there is a block for the indirect goto.
1622 if (!IndirectBranch)
1623 GetIndirectGotoBlock();
1625 llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
1627 // Make sure the indirect branch includes all of the address-taken blocks.
1628 IndirectBranch->addDestination(BB);
1629 return llvm::BlockAddress::get(CurFn, BB);
1632 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
1633 // If we already made the indirect branch for indirect goto, return its block.
1634 if (IndirectBranch) return IndirectBranch->getParent();
1636 CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
1638 // Create the PHI node that indirect gotos will add entries to.
1639 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
1640 "indirect.goto.dest");
1642 // Create the indirect branch instruction.
1643 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
1644 return IndirectBranch->getParent();
1647 /// Computes the length of an array in elements, as well as the base
1648 /// element type and a properly-typed first element pointer.
1649 llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
1652 const ArrayType *arrayType = origArrayType;
1654 // If it's a VLA, we have to load the stored size. Note that
1655 // this is the size of the VLA in bytes, not its size in elements.
1656 llvm::Value *numVLAElements = nullptr;
1657 if (isa<VariableArrayType>(arrayType)) {
1658 numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first;
1660 // Walk into all VLAs. This doesn't require changes to addr,
1661 // which has type T* where T is the first non-VLA element type.
1663 QualType elementType = arrayType->getElementType();
1664 arrayType = getContext().getAsArrayType(elementType);
1666 // If we only have VLA components, 'addr' requires no adjustment.
1668 baseType = elementType;
1669 return numVLAElements;
1671 } while (isa<VariableArrayType>(arrayType));
1673 // We get out here only if we find a constant array type
1677 // We have some number of constant-length arrays, so addr should
1678 // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
1679 // down to the first element of addr.
1680 SmallVector<llvm::Value*, 8> gepIndices;
1682 // GEP down to the array type.
1683 llvm::ConstantInt *zero = Builder.getInt32(0);
1684 gepIndices.push_back(zero);
1686 uint64_t countFromCLAs = 1;
1689 llvm::ArrayType *llvmArrayType =
1690 dyn_cast<llvm::ArrayType>(addr.getElementType());
1691 while (llvmArrayType) {
1692 assert(isa<ConstantArrayType>(arrayType));
1693 assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
1694 == llvmArrayType->getNumElements());
1696 gepIndices.push_back(zero);
1697 countFromCLAs *= llvmArrayType->getNumElements();
1698 eltType = arrayType->getElementType();
1701 dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
1702 arrayType = getContext().getAsArrayType(arrayType->getElementType());
1703 assert((!llvmArrayType || arrayType) &&
1704 "LLVM and Clang types are out-of-synch");
1708 // From this point onwards, the Clang array type has been emitted
1709 // as some other type (probably a packed struct). Compute the array
1710 // size, and just emit the 'begin' expression as a bitcast.
1713 cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
1714 eltType = arrayType->getElementType();
1715 arrayType = getContext().getAsArrayType(eltType);
1718 llvm::Type *baseType = ConvertType(eltType);
1719 addr = Builder.CreateElementBitCast(addr, baseType, "array.begin");
1721 // Create the actual GEP.
1722 addr = Address(Builder.CreateInBoundsGEP(addr.getPointer(),
1723 gepIndices, "array.begin"),
1724 addr.getAlignment());
1729 llvm::Value *numElements
1730 = llvm::ConstantInt::get(SizeTy, countFromCLAs);
1732 // If we had any VLA dimensions, factor them in.
1734 numElements = Builder.CreateNUWMul(numVLAElements, numElements);
1739 std::pair<llvm::Value*, QualType>
1740 CodeGenFunction::getVLASize(QualType type) {
1741 const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
1742 assert(vla && "type was not a variable array type!");
1743 return getVLASize(vla);
1746 std::pair<llvm::Value*, QualType>
1747 CodeGenFunction::getVLASize(const VariableArrayType *type) {
1748 // The number of elements so far; always size_t.
1749 llvm::Value *numElements = nullptr;
1751 QualType elementType;
1753 elementType = type->getElementType();
1754 llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
1755 assert(vlaSize && "no size for VLA!");
1756 assert(vlaSize->getType() == SizeTy);
1759 numElements = vlaSize;
1761 // It's undefined behavior if this wraps around, so mark it that way.
1762 // FIXME: Teach -fsanitize=undefined to trap this.
1763 numElements = Builder.CreateNUWMul(numElements, vlaSize);
1765 } while ((type = getContext().getAsVariableArrayType(elementType)));
1767 return std::pair<llvm::Value*,QualType>(numElements, elementType);
1770 void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
1771 assert(type->isVariablyModifiedType() &&
1772 "Must pass variably modified type to EmitVLASizes!");
1774 EnsureInsertPoint();
1776 // We're going to walk down into the type and look for VLA
1779 assert(type->isVariablyModifiedType());
1781 const Type *ty = type.getTypePtr();
1782 switch (ty->getTypeClass()) {
1784 #define TYPE(Class, Base)
1785 #define ABSTRACT_TYPE(Class, Base)
1786 #define NON_CANONICAL_TYPE(Class, Base)
1787 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1788 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
1789 #include "clang/AST/TypeNodes.def"
1790 llvm_unreachable("unexpected dependent type!");
1792 // These types are never variably-modified.
1796 case Type::ExtVector:
1799 case Type::Elaborated:
1800 case Type::TemplateSpecialization:
1801 case Type::ObjCTypeParam:
1802 case Type::ObjCObject:
1803 case Type::ObjCInterface:
1804 case Type::ObjCObjectPointer:
1805 llvm_unreachable("type class is never variably-modified!");
1807 case Type::Adjusted:
1808 type = cast<AdjustedType>(ty)->getAdjustedType();
1812 type = cast<DecayedType>(ty)->getPointeeType();
1816 type = cast<PointerType>(ty)->getPointeeType();
1819 case Type::BlockPointer:
1820 type = cast<BlockPointerType>(ty)->getPointeeType();
1823 case Type::LValueReference:
1824 case Type::RValueReference:
1825 type = cast<ReferenceType>(ty)->getPointeeType();
1828 case Type::MemberPointer:
1829 type = cast<MemberPointerType>(ty)->getPointeeType();
1832 case Type::ConstantArray:
1833 case Type::IncompleteArray:
1834 // Losing element qualification here is fine.
1835 type = cast<ArrayType>(ty)->getElementType();
1838 case Type::VariableArray: {
1839 // Losing element qualification here is fine.
1840 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1842 // Unknown size indication requires no size computation.
1843 // Otherwise, evaluate and record it.
1844 if (const Expr *size = vat->getSizeExpr()) {
1845 // It's possible that we might have emitted this already,
1846 // e.g. with a typedef and a pointer to it.
1847 llvm::Value *&entry = VLASizeMap[size];
1849 llvm::Value *Size = EmitScalarExpr(size);
1852 // If the size is an expression that is not an integer constant
1853 // expression [...] each time it is evaluated it shall have a value
1854 // greater than zero.
1855 if (SanOpts.has(SanitizerKind::VLABound) &&
1856 size->getType()->isSignedIntegerType()) {
1857 SanitizerScope SanScope(this);
1858 llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
1859 llvm::Constant *StaticArgs[] = {
1860 EmitCheckSourceLocation(size->getLocStart()),
1861 EmitCheckTypeDescriptor(size->getType())
1863 EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero),
1864 SanitizerKind::VLABound),
1865 SanitizerHandler::VLABoundNotPositive, StaticArgs, Size);
1868 // Always zexting here would be wrong if it weren't
1869 // undefined behavior to have a negative bound.
1870 entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
1873 type = vat->getElementType();
1877 case Type::FunctionProto:
1878 case Type::FunctionNoProto:
1879 type = cast<FunctionType>(ty)->getReturnType();
1884 case Type::UnaryTransform:
1885 case Type::Attributed:
1886 case Type::SubstTemplateTypeParm:
1887 case Type::PackExpansion:
1888 // Keep walking after single level desugaring.
1889 type = type.getSingleStepDesugaredType(getContext());
1893 case Type::Decltype:
1895 // Stop walking: nothing to do.
1898 case Type::TypeOfExpr:
1899 // Stop walking: emit typeof expression.
1900 EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
1904 type = cast<AtomicType>(ty)->getValueType();
1908 type = cast<PipeType>(ty)->getElementType();
1911 } while (type->isVariablyModifiedType());
1914 Address CodeGenFunction::EmitVAListRef(const Expr* E) {
1915 if (getContext().getBuiltinVaListType()->isArrayType())
1916 return EmitPointerWithAlignment(E);
1917 return EmitLValue(E).getAddress();
1920 Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
1921 return EmitLValue(E).getAddress();
1924 void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
1925 const APValue &Init) {
1926 assert(!Init.isUninit() && "Invalid DeclRefExpr initializer!");
1927 if (CGDebugInfo *Dbg = getDebugInfo())
1928 if (CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
1929 Dbg->EmitGlobalVariable(E->getDecl(), Init);
1932 CodeGenFunction::PeepholeProtection
1933 CodeGenFunction::protectFromPeepholes(RValue rvalue) {
1934 // At the moment, the only aggressive peephole we do in IR gen
1935 // is trunc(zext) folding, but if we add more, we can easily
1936 // extend this protection.
1938 if (!rvalue.isScalar()) return PeepholeProtection();
1939 llvm::Value *value = rvalue.getScalarVal();
1940 if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
1942 // Just make an extra bitcast.
1943 assert(HaveInsertPoint());
1944 llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
1945 Builder.GetInsertBlock());
1947 PeepholeProtection protection;
1948 protection.Inst = inst;
1952 void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
1953 if (!protection.Inst) return;
1955 // In theory, we could try to duplicate the peepholes now, but whatever.
1956 protection.Inst->eraseFromParent();
1959 llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
1960 llvm::Value *AnnotatedVal,
1961 StringRef AnnotationStr,
1962 SourceLocation Location) {
1963 llvm::Value *Args[4] = {
1965 Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
1966 Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
1967 CGM.EmitAnnotationLineNo(Location)
1969 return Builder.CreateCall(AnnotationFn, Args);
1972 void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
1973 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1974 // FIXME We create a new bitcast for every annotation because that's what
1975 // llvm-gcc was doing.
1976 for (const auto *I : D->specific_attrs<AnnotateAttr>())
1977 EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
1978 Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
1979 I->getAnnotation(), D->getLocation());
1982 Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
1984 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1985 llvm::Value *V = Addr.getPointer();
1986 llvm::Type *VTy = V->getType();
1987 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
1990 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
1991 // FIXME Always emit the cast inst so we can differentiate between
1992 // annotation on the first field of a struct and annotation on the struct
1994 if (VTy != CGM.Int8PtrTy)
1995 V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
1996 V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation());
1997 V = Builder.CreateBitCast(V, VTy);
2000 return Address(V, Addr.getAlignment());
2003 CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
2005 CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
2007 assert(!CGF->IsSanitizerScope);
2008 CGF->IsSanitizerScope = true;
2011 CodeGenFunction::SanitizerScope::~SanitizerScope() {
2012 CGF->IsSanitizerScope = false;
2015 void CodeGenFunction::InsertHelper(llvm::Instruction *I,
2016 const llvm::Twine &Name,
2017 llvm::BasicBlock *BB,
2018 llvm::BasicBlock::iterator InsertPt) const {
2019 LoopStack.InsertHelper(I);
2020 if (IsSanitizerScope)
2021 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
2024 void CGBuilderInserter::InsertHelper(
2025 llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
2026 llvm::BasicBlock::iterator InsertPt) const {
2027 llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
2029 CGF->InsertHelper(I, Name, BB, InsertPt);
2032 static bool hasRequiredFeatures(const SmallVectorImpl<StringRef> &ReqFeatures,
2033 CodeGenModule &CGM, const FunctionDecl *FD,
2034 std::string &FirstMissing) {
2035 // If there aren't any required features listed then go ahead and return.
2036 if (ReqFeatures.empty())
2039 // Now build up the set of caller features and verify that all the required
2040 // features are there.
2041 llvm::StringMap<bool> CallerFeatureMap;
2042 CGM.getFunctionFeatureMap(CallerFeatureMap, FD);
2044 // If we have at least one of the features in the feature list return
2045 // true, otherwise return false.
2047 ReqFeatures.begin(), ReqFeatures.end(), [&](StringRef Feature) {
2048 SmallVector<StringRef, 1> OrFeatures;
2049 Feature.split(OrFeatures, "|");
2050 return std::any_of(OrFeatures.begin(), OrFeatures.end(),
2051 [&](StringRef Feature) {
2052 if (!CallerFeatureMap.lookup(Feature)) {
2053 FirstMissing = Feature.str();
2061 // Emits an error if we don't have a valid set of target features for the
2063 void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
2064 const FunctionDecl *TargetDecl) {
2065 // Early exit if this is an indirect call.
2069 // Get the current enclosing function if it exists. If it doesn't
2070 // we can't check the target features anyhow.
2071 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl);
2075 // Grab the required features for the call. For a builtin this is listed in
2076 // the td file with the default cpu, for an always_inline function this is any
2077 // listed cpu and any listed features.
2078 unsigned BuiltinID = TargetDecl->getBuiltinID();
2079 std::string MissingFeature;
2081 SmallVector<StringRef, 1> ReqFeatures;
2082 const char *FeatureList =
2083 CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
2084 // Return if the builtin doesn't have any required features.
2085 if (!FeatureList || StringRef(FeatureList) == "")
2087 StringRef(FeatureList).split(ReqFeatures, ",");
2088 if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
2089 CGM.getDiags().Report(E->getLocStart(), diag::err_builtin_needs_feature)
2090 << TargetDecl->getDeclName()
2091 << CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
2093 } else if (TargetDecl->hasAttr<TargetAttr>()) {
2094 // Get the required features for the callee.
2095 SmallVector<StringRef, 1> ReqFeatures;
2096 llvm::StringMap<bool> CalleeFeatureMap;
2097 CGM.getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
2098 for (const auto &F : CalleeFeatureMap) {
2099 // Only positive features are "required".
2101 ReqFeatures.push_back(F.getKey());
2103 if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
2104 CGM.getDiags().Report(E->getLocStart(), diag::err_function_needs_feature)
2105 << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
2109 void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
2110 if (!CGM.getCodeGenOpts().SanitizeStats)
2113 llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
2114 IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
2115 CGM.getSanStats().create(IRB, SSK);
2118 llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) {
2119 if (CGDebugInfo *DI = getDebugInfo())
2120 return DI->SourceLocToDebugLoc(Location);
2122 return llvm::DebugLoc();