30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/IR/MDBuilder.h"
33 #include "llvm/IR/Operator.h"
34 using namespace clang;
35 using namespace CodeGen;
37 CodeGenFunction::CodeGenFunction(
CodeGenModule &cgm,
bool suppressNewContext)
39 Builder(cgm.getModule().getContext(), llvm::ConstantFolder(),
41 CurFn(nullptr), CapturedStmtInfo(nullptr),
42 SanOpts(CGM.getLangOpts().Sanitize), IsSanitizerScope(
false),
44 IsOutlinedSEHHelper(
false), BlockInfo(nullptr), BlockPointer(nullptr),
45 LambdaThisCaptureField(nullptr), NormalCleanupDest(nullptr),
46 NextCleanupDestIndex(1), FirstBlockInfo(nullptr), EHResumeBlock(nullptr),
47 ExceptionSlot(nullptr), EHSelectorSlot(nullptr),
48 DebugInfo(CGM.getModuleDebugInfo()),
49 DisableDebugInfo(
false), DidCallStackSave(
false), IndirectBranch(nullptr),
50 PGO(cgm), SwitchInsn(nullptr), SwitchWeights(nullptr),
51 CaseRangeBlock(nullptr), UnreachableBlock(nullptr), NumReturnExprs(0),
52 NumSimpleReturnExprs(0), CXXABIThisDecl(nullptr),
53 CXXABIThisValue(nullptr), CXXThisValue(nullptr),
54 CXXDefaultInitExprThis(nullptr), CXXStructorImplicitParamDecl(nullptr),
55 CXXStructorImplicitParamValue(nullptr), OutermostConditional(nullptr),
56 CurLexicalScope(nullptr), TerminateLandingPad(nullptr),
57 TerminateHandler(nullptr), TrapBB(nullptr) {
58 if (!suppressNewContext)
61 llvm::FastMathFlags FMF;
63 FMF.setUnsafeAlgebra();
72 FMF.setNoSignedZeros();
75 FMF.setAllowReciprocal();
99 if (MaxAlign && Alignment.
getQuantity() > MaxAlign &&
118 #define TYPE(name, parent)
119 #define ABSTRACT_TYPE(name, parent)
120 #define NON_CANONICAL_TYPE(name, parent) case Type::name:
121 #define DEPENDENT_TYPE(name, parent) case Type::name:
122 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
123 #include "clang/AST/TypeNodes.def"
124 llvm_unreachable(
"non-canonical or dependent type in IR-generation");
127 llvm_unreachable(
"undeduced auto type in IR-generation");
132 case Type::BlockPointer:
133 case Type::LValueReference:
134 case Type::RValueReference:
135 case Type::MemberPointer:
137 case Type::ExtVector:
138 case Type::FunctionProto:
139 case Type::FunctionNoProto:
141 case Type::ObjCObjectPointer:
149 case Type::ConstantArray:
150 case Type::IncompleteArray:
151 case Type::VariableArray:
153 case Type::ObjCObject:
154 case Type::ObjCInterface:
159 type = cast<AtomicType>(
type)->getValueType();
162 llvm_unreachable(
"unknown type kind!");
169 llvm::BasicBlock *CurBB =
Builder.GetInsertBlock();
172 assert(!CurBB->getTerminator() &&
"Unexpected terminated block.");
181 return llvm::DebugLoc();
188 llvm::BranchInst *BI =
190 if (BI && BI->isUnconditional() &&
194 llvm::DebugLoc Loc = BI->getDebugLoc();
195 Builder.SetInsertPoint(BI->getParent());
196 BI->eraseFromParent();
207 return llvm::DebugLoc();
212 if (!BB->use_empty())
213 return CGF.
CurFn->getBasicBlockList().push_back(BB);
218 assert(BreakContinueStack.empty() &&
219 "mismatched push/pop in break/continue stack!");
221 bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
222 && NumSimpleReturnExprs == NumReturnExprs
237 if (OnlySimpleReturnStmts)
238 DI->EmitLocation(
Builder, LastStopPoint);
240 DI->EmitLocation(
Builder, EndLoc);
248 bool HasOnlyLifetimeMarkers =
250 bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
255 if (OnlySimpleReturnStmts)
256 DI->EmitLocation(
Builder, EndLoc);
278 "did not remove all scopes from cleanup stack!");
282 if (IndirectBranch) {
289 if (!EscapedLocals.empty()) {
293 EscapeArgs.resize(EscapedLocals.size());
294 for (
auto &Pair : EscapedLocals)
295 EscapeArgs[Pair.second] = Pair.first;
296 llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
304 Ptr->eraseFromParent();
308 if (IndirectBranch) {
309 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
310 if (PN->getNumIncomingValues() == 0) {
311 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
312 PN->eraseFromParent();
324 for (
SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
325 I = DeferredReplacements.begin(),
326 E = DeferredReplacements.end();
328 I->first->replaceAllUsesWith(I->second);
329 I->first->eraseFromParent();
348 llvm::PointerType *PointerTy =
Int8PtrTy;
349 llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy };
350 llvm::FunctionType *FunctionTy =
351 llvm::FunctionType::get(
VoidTy, ProfileFuncArgs,
false);
354 llvm::CallInst *CallSite =
Builder.CreateCall(
356 llvm::ConstantInt::get(
Int32Ty, 0),
360 llvm::ConstantExpr::getBitCast(
CurFn, PointerTy),
368 llvm::FunctionType *FTy = llvm::FunctionType::get(
VoidTy,
false);
370 llvm::Constant *MCountFn =
390 addressQuals.push_back(llvm::MDString::get(Context,
"kernel_arg_addr_space"));
394 accessQuals.push_back(llvm::MDString::get(Context,
"kernel_arg_access_qual"));
398 argTypeNames.push_back(llvm::MDString::get(Context,
"kernel_arg_type"));
402 argBaseTypeNames.push_back(
403 llvm::MDString::get(Context,
"kernel_arg_base_type"));
407 argTypeQuals.push_back(llvm::MDString::get(Context,
"kernel_arg_type_qual"));
411 argNames.push_back(llvm::MDString::get(Context,
"kernel_arg_name"));
413 for (
unsigned i = 0, e = FD->
getNumParams(); i != e; ++i) {
416 std::string typeQuals;
422 addressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(
426 std::string typeName =
430 std::string::size_type pos = typeName.find(
"unsigned");
431 if (pointeeTy.
isCanonical() && pos != std::string::npos)
432 typeName.erase(pos+1, 8);
434 argTypeNames.push_back(llvm::MDString::get(Context, typeName));
436 std::string baseTypeName =
442 pos = baseTypeName.find(
"unsigned");
443 if (pos != std::string::npos)
444 baseTypeName.erase(pos+1, 8);
446 argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
450 typeQuals =
"restrict";
453 typeQuals += typeQuals.empty() ?
"const" :
" const";
455 typeQuals += typeQuals.empty() ?
"volatile" :
" volatile";
457 uint32_t AddrSpc = 0;
462 addressQuals.push_back(
463 llvm::ConstantAsMetadata::get(Builder.getInt32(AddrSpc)));
469 std::string::size_type pos = typeName.find(
"unsigned");
471 typeName.erase(pos+1, 8);
473 argTypeNames.push_back(llvm::MDString::get(Context, typeName));
475 std::string baseTypeName =
479 pos = baseTypeName.find(
"unsigned");
480 if (pos != std::string::npos)
481 baseTypeName.erase(pos+1, 8);
483 argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
489 typeQuals += typeQuals.empty() ?
"volatile" :
" volatile";
492 argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals));
496 const OpenCLImageAccessAttr *A = parm->
getAttr<OpenCLImageAccessAttr>();
497 if (A && A->isWriteOnly())
498 accessQuals.push_back(llvm::MDString::get(Context,
"write_only"));
500 accessQuals.push_back(llvm::MDString::get(Context,
"read_only"));
503 accessQuals.push_back(llvm::MDString::get(Context,
"none"));
506 argNames.push_back(llvm::MDString::get(Context, parm->
getName()));
509 kernelMDArgs.push_back(llvm::MDNode::get(Context, addressQuals));
510 kernelMDArgs.push_back(llvm::MDNode::get(Context, accessQuals));
511 kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeNames));
512 kernelMDArgs.push_back(llvm::MDNode::get(Context, argBaseTypeNames));
513 kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeQuals));
515 kernelMDArgs.push_back(llvm::MDNode::get(Context, argNames));
518 void CodeGenFunction::EmitOpenCLKernelMetadata(
const FunctionDecl *FD,
521 if (!FD->
hasAttr<OpenCLKernelAttr>())
527 kernelMDArgs.push_back(llvm::ConstantAsMetadata::get(Fn));
532 if (
const VecTypeHintAttr *A = FD->
getAttr<VecTypeHintAttr>()) {
533 QualType hintQTy = A->getTypeHint();
535 bool isSignedInteger =
538 llvm::Metadata *attrMDArgs[] = {
539 llvm::MDString::get(Context,
"vec_type_hint"),
540 llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
542 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
543 llvm::IntegerType::get(Context, 32),
544 llvm::APInt(32, (uint64_t)(isSignedInteger ? 1 : 0))))};
545 kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
548 if (
const WorkGroupSizeHintAttr *A = FD->
getAttr<WorkGroupSizeHintAttr>()) {
549 llvm::Metadata *attrMDArgs[] = {
550 llvm::MDString::get(Context,
"work_group_size_hint"),
551 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getXDim())),
552 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getYDim())),
553 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getZDim()))};
554 kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
557 if (
const ReqdWorkGroupSizeAttr *A = FD->
getAttr<ReqdWorkGroupSizeAttr>()) {
558 llvm::Metadata *attrMDArgs[] = {
559 llvm::MDString::get(Context,
"reqd_work_group_size"),
560 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getXDim())),
561 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getYDim())),
562 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getZDim()))};
563 kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
566 llvm::MDNode *kernelMDNode = llvm::MDNode::get(Context, kernelMDArgs);
567 llvm::NamedMDNode *OpenCLKernelMetadata =
568 CGM.
getModule().getOrInsertNamedMetadata(
"opencl.kernels");
569 OpenCLKernelMetadata->addOperand(kernelMDNode);
574 const Stmt *Body =
nullptr;
575 if (
auto *FD = dyn_cast_or_null<FunctionDecl>(F))
577 else if (
auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
578 Body = OMD->getBody();
580 if (
auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
581 auto LastStmt = CS->body_rbegin();
582 if (LastStmt != CS->body_rend())
583 return isa<ReturnStmt>(*LastStmt);
596 "Do not use a CodeGenFunction object for more than one function");
600 DidCallStackSave =
false;
606 assert(
CurFn->isDeclaration() &&
"Function already has body?");
618 if (
SanOpts.
hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
619 Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
621 Fn->addFnAttr(llvm::Attribute::SanitizeThread);
623 Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
625 Fn->addFnAttr(llvm::Attribute::SafeStack);
630 if (
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
633 if (RI->isInlineSpecified()) {
634 Fn->addFnAttr(llvm::Attribute::InlineHint);
637 }
else if (!FD->
hasAttr<AlwaysInlineAttr>())
638 Fn->addFnAttr(llvm::Attribute::NoInline);
643 if (
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
644 EmitOpenCLKernelMetadata(FD, Fn);
650 if (
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
651 if (llvm::Constant *PrologueSig =
653 llvm::Constant *FTRTTIConst =
655 llvm::Constant *PrologueStructElems[] = { PrologueSig, FTRTTIConst };
656 llvm::Constant *PrologueStructConst =
657 llvm::ConstantStruct::getAnon(PrologueStructElems,
true);
658 Fn->setPrologueData(PrologueStructConst);
670 if (
Builder.isNamePreserving())
675 Builder.SetInsertPoint(EntryBB);
680 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
682 ArgTypes.push_back((*i)->getType());
688 DI->EmitFunctionStart(GD, Loc, StartLoc, FnType,
CurFn,
Builder);
708 auto AI =
CurFn->arg_begin();
716 llvm::Function::arg_iterator EI =
CurFn->arg_end();
737 if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
752 if (FD->hasCapturedVLAType()) {
755 auto VAT = FD->getCapturedVLAType();
756 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
763 CXXThisValue = CXXABIThisValue;
769 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
777 if (
const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
778 Ty = PVD->getOriginalType();
787 DI->EmitLocation(
Builder, StartLoc);
805 llvm::BasicBlock *SkipCountBB =
nullptr;
827 if (F->mayBeOverridden())
return;
829 for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
830 for (llvm::BasicBlock::iterator
831 BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
832 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI)) {
833 if (!Call->doesNotThrow())
835 }
else if (isa<llvm::ResumeInst>(&*BI)) {
838 F->setDoesNotThrow();
846 if (FD->
hasAttr<NoDebugAttr>())
864 if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
868 if (
Stmt *Body = FD->
getBody()) BodyRange = Body->getSourceRange();
869 CurEHLocation = BodyRange.
getEnd();
881 if (SpecDecl->hasBody(SpecDecl))
882 Loc = SpecDecl->getLocation();
890 if (isa<CXXDestructorDecl>(FD))
892 else if (isa<CXXConstructorDecl>(FD))
898 else if (isa<CXXConversionDecl>(FD) &&
899 cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) {
903 }
else if (isa<CXXMethodDecl>(FD) &&
904 cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
908 }
else if (FD->
isDefaulted() && isa<CXXMethodDecl>(FD) &&
909 (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
910 cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
917 llvm_unreachable(
"no definition for emitted function");
930 EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
945 if (!
CurFn->doesNotThrow())
954 if (!S)
return false;
961 if (isa<LabelStmt>(S))
966 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
970 if (isa<SwitchStmt>(S))
971 IgnoreCaseStmts =
true;
974 for (
const Stmt *SubStmt : S->children())
986 if (!S)
return false;
990 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
994 if (isa<BreakStmt>(S))
998 for (
const Stmt *SubStmt : S->children())
1011 llvm::APSInt ResultInt;
1015 ResultBool = ResultInt.getBoolValue();
1044 llvm::BasicBlock *TrueBlock,
1045 llvm::BasicBlock *FalseBlock,
1046 uint64_t TrueCount) {
1049 if (
const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
1052 if (CondBOp->getOpcode() ==
BO_LAnd) {
1055 bool ConstantBool =
false;
1098 if (CondBOp->getOpcode() ==
BO_LOr) {
1101 bool ConstantBool =
false;
1127 uint64_t RHSCount = TrueCount - LHSCount;
1149 if (
const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1151 if (CondUOp->getOpcode() ==
UO_LNot) {
1174 uint64_t LHSScaledTrueCount = 0;
1178 LHSScaledTrueCount = TrueCount * LHSRatio;
1187 LHSScaledTrueCount);
1194 TrueCount - LHSScaledTrueCount);
1200 if (
const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
1213 llvm::MDNode *Weights =
1214 createProfileWeights(TrueCount, CurrentCount - TrueCount);
1222 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights);
1241 std::pair<CharUnits,CharUnits> baseSizeAndAlign
1247 = llvm::ConstantInt::get(CGF.
IntPtrTy, baseSizeAndAlign.first.getQuantity());
1249 llvm::Type *i8p = Builder.getInt8PtrTy();
1251 llvm::Value *begin = Builder.CreateBitCast(dest, i8p,
"vla.begin");
1252 llvm::Value *end = Builder.CreateInBoundsGEP(dest, sizeInChars,
"vla.end");
1254 llvm::BasicBlock *originBB = CGF.
Builder.GetInsertBlock();
1262 llvm::PHINode *cur = Builder.CreatePHI(i8p, 2,
"vla.cur");
1263 cur->addIncoming(begin, originBB);
1266 Builder.CreateMemCpy(cur, src, baseSizeInChars,
1267 baseSizeAndAlign.second.getQuantity(),
1271 llvm::Value *next = Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(),
1272 cur, 1,
"vla.next");
1275 llvm::Value *done = Builder.CreateICmpEQ(next, end,
"vla-init.isdone");
1276 Builder.CreateCondBr(done, contBB, loopBB);
1277 cur->addIncoming(next, loopBB);
1287 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
1294 cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace();
1295 llvm::Type *BP =
Builder.getInt8PtrTy(DestAS);
1296 if (DestPtr->getType() != BP)
1297 DestPtr =
Builder.CreateBitCast(DestPtr, BP);
1300 std::pair<CharUnits, CharUnits>
TypeInfo =
1312 dyn_cast_or_null<VariableArrayType>(
1316 std::tie(numElts, eltType) =
getVLASize(vlaType);
1320 if (!eltSize.
isOne())
1341 llvm::GlobalVariable *NullVariable =
1342 new llvm::GlobalVariable(
CGM.
getModule(), NullConstant->getType(),
1344 llvm::GlobalVariable::PrivateLinkage,
1345 NullConstant, Twine());
1365 if (!IndirectBranch)
1371 IndirectBranch->addDestination(BB);
1372 return llvm::BlockAddress::get(
CurFn, BB);
1377 if (IndirectBranch)
return IndirectBranch->getParent();
1383 "indirect.goto.dest");
1386 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
1387 return IndirectBranch->getParent();
1395 const ArrayType *arrayType = origArrayType;
1400 if (isa<VariableArrayType>(arrayType)) {
1401 numVLAElements =
getVLASize(cast<VariableArrayType>(arrayType)).first;
1411 baseType = elementType;
1412 return numVLAElements;
1414 }
while (isa<VariableArrayType>(arrayType));
1426 llvm::ConstantInt *zero =
Builder.getInt32(0);
1427 gepIndices.push_back(zero);
1429 uint64_t countFromCLAs = 1;
1432 llvm::ArrayType *llvmArrayType =
1433 dyn_cast<llvm::ArrayType>(
1435 while (llvmArrayType) {
1436 assert(isa<ConstantArrayType>(arrayType));
1437 assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
1438 == llvmArrayType->getNumElements());
1440 gepIndices.push_back(zero);
1441 countFromCLAs *= llvmArrayType->getNumElements();
1445 dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
1447 assert((!llvmArrayType || arrayType) &&
1448 "LLVM and Clang types are out-of-synch");
1457 cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
1462 unsigned AddressSpace = addr->getType()->getPointerAddressSpace();
1463 llvm::Type *BaseType =
ConvertType(eltType)->getPointerTo(AddressSpace);
1464 addr =
Builder.CreateBitCast(addr, BaseType,
"array.begin");
1467 addr =
Builder.CreateInBoundsGEP(addr, gepIndices,
"array.begin");
1473 = llvm::ConstantInt::get(
SizeTy, countFromCLAs);
1477 numElements =
Builder.CreateNUWMul(numVLAElements, numElements);
1482 std::pair<llvm::Value*, QualType>
1485 assert(vla &&
"type was not a variable array type!");
1489 std::pair<llvm::Value*, QualType>
1498 assert(vlaSize &&
"no size for VLA!");
1499 assert(vlaSize->getType() ==
SizeTy);
1502 numElements = vlaSize;
1506 numElements =
Builder.CreateNUWMul(numElements, vlaSize);
1508 }
while ((type =
getContext().getAsVariableArrayType(elementType)));
1510 return std::pair<llvm::Value*,QualType>(numElements, elementType);
1515 "Must pass variably modified type to EmitVLASizes!");
1525 switch (ty->getTypeClass()) {
1527 #define TYPE(Class, Base)
1528 #define ABSTRACT_TYPE(Class, Base)
1529 #define NON_CANONICAL_TYPE(Class, Base)
1530 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1531 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
1532 #include "clang/AST/TypeNodes.def"
1533 llvm_unreachable(
"unexpected dependent type!");
1539 case Type::ExtVector:
1542 case Type::Elaborated:
1543 case Type::TemplateSpecialization:
1544 case Type::ObjCObject:
1545 case Type::ObjCInterface:
1546 case Type::ObjCObjectPointer:
1547 llvm_unreachable(
"type class is never variably-modified!");
1549 case Type::Adjusted:
1550 type = cast<AdjustedType>(ty)->getAdjustedType();
1554 type = cast<DecayedType>(ty)->getPointeeType();
1558 type = cast<PointerType>(ty)->getPointeeType();
1561 case Type::BlockPointer:
1562 type = cast<BlockPointerType>(ty)->getPointeeType();
1565 case Type::LValueReference:
1566 case Type::RValueReference:
1567 type = cast<ReferenceType>(ty)->getPointeeType();
1570 case Type::MemberPointer:
1571 type = cast<MemberPointerType>(ty)->getPointeeType();
1574 case Type::ConstantArray:
1575 case Type::IncompleteArray:
1580 case Type::VariableArray: {
1598 size->getType()->isSignedIntegerType()) {
1600 llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
1601 llvm::Constant *StaticArgs[] = {
1606 SanitizerKind::VLABound),
1607 "vla_bound_not_positive", StaticArgs, Size);
1619 case Type::FunctionProto:
1620 case Type::FunctionNoProto:
1621 type = cast<FunctionType>(ty)->getReturnType();
1626 case Type::UnaryTransform:
1627 case Type::Attributed:
1628 case Type::SubstTemplateTypeParm:
1629 case Type::PackExpansion:
1635 case Type::Decltype:
1640 case Type::TypeOfExpr:
1646 type = cast<AtomicType>(ty)->getValueType();
1653 if (
getContext().getBuiltinVaListType()->isArrayType())
1659 llvm::Constant *Init) {
1660 assert (Init &&
"Invalid DeclRefExpr initializer!");
1663 Dbg->EmitGlobalVariable(E->
getDecl(), Init);
1678 llvm::Instruction *inst =
new llvm::BitCastInst(value, value->getType(),
"",
1682 protection.Inst = inst;
1687 if (!protection.Inst)
return;
1690 protection.Inst->eraseFromParent();
1695 StringRef AnnotationStr,
1703 return Builder.CreateCall(AnnotationFn, Args);
1707 assert(D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
1718 assert(D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
1719 llvm::Type *VTy = V->getType();
1730 V =
Builder.CreateBitCast(V, VTy);
1745 CGF->IsSanitizerScope =
false;
1749 const llvm::Twine &Name,
1750 llvm::BasicBlock *BB,
1751 llvm::BasicBlock::iterator InsertPt)
const {
1757 template <
bool PreserveNames>
1759 llvm::Instruction *I,
const llvm::Twine &Name, llvm::BasicBlock *BB,
1760 llvm::BasicBlock::iterator InsertPt)
const {
1761 llvm::IRBuilderDefaultInserter<PreserveNames>::InsertHelper(I, Name, BB,
1764 CGF->InsertHelper(I, Name, BB, InsertPt);
1768 #define PreserveNames false
1770 #define PreserveNames true
1773 llvm::Instruction *I,
const llvm::Twine &Name, llvm::BasicBlock *BB,
1774 llvm::BasicBlock::iterator InsertPt)
const;
1775 #undef PreserveNames
unsigned getAddressSpace() const
getAddressSpace - Return the address space of this type.
Defines the clang::ASTContext interface.
SourceLocation getEnd() const
void end(CodeGenFunction &CGF)
StringRef getName() const
CodeGenTypes & getTypes()
llvm::Type * ConvertTypeForMem(QualType T)
void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock, uint64_t TrueCount)
CanQualType getReturnType() const
unsigned getInAllocaFieldIndex() const
llvm::Constant * EmitCheckTypeDescriptor(QualType T)
Emit a description of a type in a format suitable for passing to a runtime sanitizer handler...
llvm::Module & getModule() const
void EmitFunctionInstrumentation(const char *Fn)
bool isOne() const
isOne - Test whether the quantity equals one.
void checkGlobalDecl(GlobalDecl GD)
Check if we need to emit coverage mapping for a given declaration.
virtual void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy, FunctionArgList &Params)=0
const TargetInfo & getTarget() const
static bool endsWithReturn(const Decl *F)
Determine whether the function F ends with a return stmt.
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
std::string getAsString() const
bool ShouldInstrumentFunction()
void GenerateCode(GlobalDecl GD, llvm::Function *Fn, const CGFunctionInfo &FnInfo)
const LangOptions & getLangOpts() const
llvm::Value * getAddress() const
RAII object to set/unset CodeGenFunction::IsSanitizerScope.
ExtProtoInfo - Extra information about a function prototype.
uint64_t getProfileCount(const Stmt *S)
Get the profiler's count for the given statement.
QualType getThisType(ASTContext &C) const
Returns the type of the this pointer.
llvm::CallInst * EmitTrapCall(llvm::Intrinsic::ID IntrID)
Emit a call to trap or debugtrap and attach function attribute "trap-func-name" if specified...
void EmitVariablyModifiedType(QualType Ty)
void setCurrentProfileCount(uint64_t Count)
Set the profiler's current count.
bool IsSanitizerScope
True if CodeGen currently emits code implementing sanitizer checks.
llvm::Value * ReturnValue
Describes how types, statements, expressions, and declarations should be printed. ...
llvm::Type * ConvertTypeForMem(QualType T)
A C++ throw-expression (C++ [except.throw]).
ParmVarDecl - Represents a parameter to a function.
bool isObjCRetainableType() const
static void destroyBlockInfos(CGBlockInfo *info)
Destroy a chain of block layouts.
void emitImplicitAssignmentOperatorBody(FunctionArgList &Args)
EHScopeStack::stable_iterator PrologueCleanupDepth
virtual bool hasMostDerivedReturn(GlobalDecl GD) const
JumpDest getJumpDestForLabel(const LabelDecl *S)
llvm::DenseMap< const VarDecl *, FieldDecl * > LambdaCaptureFields
An object to manage conditionally-evaluated expressions.
PeepholeProtection protectFromPeepholes(RValue rvalue)
CGBlockInfo * FirstBlockInfo
FirstBlockInfo - The head of a singly-linked-list of block layouts.
void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc, SourceLocation EndLoc)
CGDebugInfo * getDebugInfo()
Expr * getSizeExpr() const
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
LValue EmitLValueForLambdaField(const FieldDecl *Field)
static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType, llvm::Value *dest, llvm::Value *src, llvm::Value *sizeInChars)
QualType getReturnType() const
llvm::IntegerType * SizeTy
void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB, llvm::BasicBlock::iterator InsertPt) const
CGBuilder insert helper. This function is called after an instruction is created using Builder...
SanitizerMask Mask
Bitmask of enabled sanitizers.
const Decl * getDecl() const
virtual void EmitInstanceFunctionProlog(CodeGenFunction &CGF)=0
Emit the ABI-specific prolog for the function.
CGCUDARuntime & getCUDARuntime()
Return a reference to the configured CUDA runtime.
static bool hasScalarEvaluationKind(QualType T)
const LangOptions & getLangOpts() const
virtual bool isTypeInfoCalculable(QualType Ty) const
const CXXRecordDecl * getParent() const
field_range fields() const
const ArrayType * getAsArrayType(QualType T) const
A builtin binary operation expression such as "x + y" or "x <= y".
FunctionDecl * getTemplateInstantiationPattern() const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
void incrementProfileCounter(const Stmt *S)
Increment the profiler's counter for the given statement.
void EmitStmt(const Stmt *S)
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
TypeClass getTypeClass() const
GlobalDecl CurGD
CurGD - The GlobalDecl for the current function being compiled.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts=false)
llvm::DebugLoc EmitReturnBlock()
Emit the unified return block, trying to avoid its emission when possible.
uint64_t getCurrentProfileCount()
virtual void emitDeviceStub(CodeGenFunction &CGF, FunctionArgList &Args)=0
Emits a kernel launch stub.
std::pair< CharUnits, CharUnits > getTypeInfoInChars(const Type *T) const
void begin(CodeGenFunction &CGF)
param_iterator param_begin()
void EmitDeclRefExprDbgValue(const DeclRefExpr *E, llvm::Constant *Init)
void EmitCheck(ArrayRef< std::pair< llvm::Value *, SanitizerMask >> Checked, StringRef CheckName, ArrayRef< llvm::Constant * > StaticArgs, ArrayRef< llvm::Value * > DynamicArgs)
Create a basic block that will call a handler function in a sanitizer runtime with the provided argum...
llvm::CallInst * EmitNounwindRuntimeCall(llvm::Value *callee, const Twine &name="")
const TargetCodeGenInfo & getTargetCodeGenInfo()
void clear()
Disable all sanitizers.
static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB)
QualType getPointeeType() const
static TypeEvaluationKind getEvaluationKind(QualType T)
llvm::Constant * EmitAnnotationUnit(SourceLocation Loc)
Emit the annotation's translation unit.
static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn, CodeGenModule &CGM, llvm::LLVMContext &Context, SmallVector< llvm::Metadata *, 5 > &kernelMDArgs, CGBuilderTy &Builder, ASTContext &ASTCtx)
llvm::BasicBlock * EHResumeBlock
EHResumeBlock - Unified block containing a call to llvm.eh.resume.
bool empty() const
Determines whether the exception-scopes stack is empty.
CGCXXABI & getCXXABI() const
llvm::Value * emitArrayLength(const ArrayType *arrayType, QualType &baseType, llvm::Value *&addr)
const ParmVarDecl * getParamDecl(unsigned i) const
static void TryMarkNoThrow(llvm::Function *F)
ASTContext & getContext() const
llvm::BasicBlock * getBlock() const
llvm::Value * EmitCompoundStmtWithoutScope(const CompoundStmt &S, bool GetLast=false, AggValueSlot AVS=AggValueSlot::ignored())
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
stable_iterator stable_begin() const
llvm::LLVMContext & getLLVMContext()
llvm::BasicBlock * GetIndirectGotoBlock()
llvm::IntegerType * Int32Ty
void EmitConstructorBody(FunctionArgList &Args)
EmitConstructorBody - Emits the body of the current constructor.
llvm::Constant * EmitAnnotationString(StringRef Str)
Emit an annotation string.
bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
virtual llvm::Constant * getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const
virtual bool HasThisReturn(GlobalDecl GD) const
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T)
bool containsOnlyLifetimeMarkers(stable_iterator Old) const
void EmitMCountInstrumentation()
EmitMCountInstrumentation - Emit call to .mcount.
void EmitLambdaToBlockPointerBody(FunctionArgList &Args)
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys=None)
QualType getElementType() const
llvm::IRBuilder< PreserveNames, llvm::ConstantFolder, CGBuilderInserterTy > CGBuilderTy
virtual void startNewFunction()
const clang::PrintingPolicy & getPrintingPolicy() const
SanitizerScope(CodeGenFunction *CGF)
Stmt * getBody(const FunctionDecl *&Definition) const
bool HaveInsertPoint() const
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl. It will iterate at least once ...
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
bool hasOneOf(SanitizerMask K) const
Check if one or more sanitizers are enabled.
llvm::Constant * CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeSet ExtraAttrs=llvm::AttributeSet())
Create a new runtime function with the specified type and name.
llvm::AllocaInst * CreateIRTemp(QualType T, const Twine &Name="tmp")
ASTContext & getContext() const
Encodes a location in the source. The SourceManager can decode this to get at the full include stack...
unsigned getNumParams() const
const Type * getTypePtr() const
llvm::Value * EvaluateExprAsBool(const Expr *E)
bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result)
Represents a static or instance method of a struct/union/class.
bool isReturnsRetained() const
llvm::Value * EmitVAListRef(const Expr *E)
void EmitNullInitialization(llvm::Value *DestPtr, QualType Ty)
SanitizerSet SanOpts
Sanitizers enabled for this function.
llvm::Constant * GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH=false)
Get the address of the RTTI descriptor for the given type.
const CodeGenOptions & getCodeGenOpts() const
static LValue MakeAddr(llvm::Value *address, QualType type, CharUnits alignment, ASTContext &Context, llvm::MDNode *TBAAInfo=nullptr)
void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn, const CGFunctionInfo &FnInfo, const FunctionArgList &Args, SourceLocation Loc=SourceLocation(), SourceLocation StartLoc=SourceLocation())
Emit code for the start of a function.
const LangOptions & getLangOpts() const
SourceLocation getBegin() const
void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB, llvm::BasicBlock::iterator InsertPt) const
This forwards to CodeGenFunction::InsertHelper.
MangleContext & getMangleContext()
Gets the mangle context.
void getCaptureFields(llvm::DenseMap< const VarDecl *, FieldDecl * > &Captures, FieldDecl *&ThisCapture) const
For a closure type, retrieve the mapping from captured variables and this to the non-static data memb...
JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target)
llvm::Constant * EmitAnnotationLineNo(SourceLocation L)
Emit the annotation line number.
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
const CGFunctionInfo * CurFnInfo
void EmitStartEHSpec(const Decl *D)
EmitStartEHSpec - Emit the start of the exception spec.
void FinishFunction(SourceLocation EndLoc=SourceLocation())
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
This is an IRBuilder insertion helper that forwards to CodeGenFunction::InsertHelper, which adds necessary metadata to instructions.
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
bool isSRetAfterThis() const
llvm::Value * EmitFieldAnnotations(const FieldDecl *D, llvm::Value *V)
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn't support the specified stmt yet.
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
static const Type * getElementType(const Expr *BaseExpr)
bool isZero() const
isZero - Test whether the quantity equals zero.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
virtual ~CGCapturedStmtInfo()
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
llvm::Value * EmitAnnotationCall(llvm::Value *AnnotationFn, llvm::Value *AnnotatedVal, StringRef AnnotationStr, SourceLocation Location)
Emit an annotation call (intrinsic or builtin).
llvm::IntegerType * IntPtrTy
Decl * getNonClosureContext()
void buildThisParam(CodeGenFunction &CGF, FunctionArgList &Params)
Build a parameter variable suitable for 'this'.
llvm::Constant * EmitNullConstant(QualType T)
llvm::SmallVector< char, 256 > LifetimeExtendedCleanupStack
bool isLambda() const
Determine whether this class describes a lambda function object.
bool isInSanitizerBlacklist(llvm::Function *Fn, SourceLocation Loc) const
const VariableArrayType * getAsVariableArrayType(QualType T) const
param_iterator param_end()
JumpDest ReturnBlock
ReturnBlock - Unified return block.
void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S)
QualType getCanonicalType() const
llvm::PointerType * Int8PtrTy
void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD)
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
llvm::AssertingVH< llvm::Instruction > AllocaInsertPt
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
FieldDecl * LambdaThisCaptureField
ABIArgInfo & getReturnInfo()
void EmitFunctionBody(FunctionArgList &Args, const Stmt *Body)
llvm::ConstantInt * getSize(CharUnits numChars)
Emit the given number of characters as a value of type size_t.
void InsertHelper(llvm::Instruction *I) const
Function called by the CodeGenFunction when an instruction is created.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
void unprotectFromPeepholes(PeepholeProtection protection)
void ErrorUnsupported(const Stmt *S, const char *Type)
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
BoundNodesTreeBuilder *const Builder
void EmitBranch(llvm::BasicBlock *Block)
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
llvm::Type * ConvertType(QualType T)
void EmitFunctionProlog(const CGFunctionInfo &FI, llvm::Function *Fn, const FunctionArgList &Args)
void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize)
Takes the old cleanup stack size and emits the cleanup blocks that have been added.
LValue EmitLValue(const Expr *E)
bool AutoreleaseResult
In ARC, whether we should autorelease the return value.
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
std::pair< llvm::Value *, QualType > getVLASize(const VariableArrayType *vla)
Defines the clang::TargetInfo interface.
llvm::MDNode * getTBAAInfo(QualType QTy)
unsigned getTargetAddressSpace(QualType T) const
A reference to a declared variable, function, enum, etc. [C99 6.5.1p2].
void EmitDestructorBody(FunctionArgList &Args)
EmitDestructorBody - Emits the body of the current destructor.
QualType getElementType() const
void EmitEndEHSpec(const Decl *D)
EmitEndEHSpec - Emit the end of the exception spec.
llvm::Constant * EmitCheckSourceLocation(SourceLocation Loc)
Emit a description of a source location in a format suitable for passing to a runtime sanitizer handl...
A trivial tuple used to represent a source range.
SourceLocation getLocation() const
llvm::BlockAddress * GetAddrOfLabel(const LabelDecl *L)
void EmitVarAnnotations(const VarDecl *D, llvm::Value *V)
Emit local annotations for the local variable V, declared by D.
SanitizerMetadata * getSanitizerMetadata()
bool isSignedIntegerType() const
void assignRegionCounters(const Decl *D, llvm::Function *Fn)
bool isConstQualified() const
Determine whether this type is const-qualified.
bool hasImplicitReturnZero() const
static bool containsBreak(const Stmt *S)
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
bool isZeroInitializable(QualType T)
void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint=true)
Attr - This represents one attribute.
Expr * IgnoreParens() LLVM_READONLY
bool isPointerType() const
OverloadedOperatorKind getOverloadedOperator() const