xref: /aosp_15_r20/external/clang/lib/CodeGen/CodeGenFunction.cpp (revision 67e74705e28f6214e480b399dd47ea732279e315)
1*67e74705SXin Li //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2*67e74705SXin Li //
3*67e74705SXin Li //                     The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li //
10*67e74705SXin Li // This coordinates the per-function state used while generating code.
11*67e74705SXin Li //
12*67e74705SXin Li //===----------------------------------------------------------------------===//
13*67e74705SXin Li 
14*67e74705SXin Li #include "CodeGenFunction.h"
15*67e74705SXin Li #include "CGBlocks.h"
16*67e74705SXin Li #include "CGCleanup.h"
17*67e74705SXin Li #include "CGCUDARuntime.h"
18*67e74705SXin Li #include "CGCXXABI.h"
19*67e74705SXin Li #include "CGDebugInfo.h"
20*67e74705SXin Li #include "CGOpenMPRuntime.h"
21*67e74705SXin Li #include "CodeGenModule.h"
22*67e74705SXin Li #include "CodeGenPGO.h"
23*67e74705SXin Li #include "TargetInfo.h"
24*67e74705SXin Li #include "clang/AST/ASTContext.h"
25*67e74705SXin Li #include "clang/AST/Decl.h"
26*67e74705SXin Li #include "clang/AST/DeclCXX.h"
27*67e74705SXin Li #include "clang/AST/StmtCXX.h"
28*67e74705SXin Li #include "clang/Basic/Builtins.h"
29*67e74705SXin Li #include "clang/Basic/TargetInfo.h"
30*67e74705SXin Li #include "clang/CodeGen/CGFunctionInfo.h"
31*67e74705SXin Li #include "clang/Frontend/CodeGenOptions.h"
32*67e74705SXin Li #include "clang/Sema/SemaDiagnostic.h"
33*67e74705SXin Li #include "llvm/IR/DataLayout.h"
34*67e74705SXin Li #include "llvm/IR/Intrinsics.h"
35*67e74705SXin Li #include "llvm/IR/MDBuilder.h"
36*67e74705SXin Li #include "llvm/IR/Operator.h"
37*67e74705SXin Li using namespace clang;
38*67e74705SXin Li using namespace CodeGen;
39*67e74705SXin Li 
CodeGenFunction(CodeGenModule & cgm,bool suppressNewContext)40*67e74705SXin Li CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
41*67e74705SXin Li     : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
42*67e74705SXin Li       Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
43*67e74705SXin Li               CGBuilderInserterTy(this)),
44*67e74705SXin Li       CurFn(nullptr), ReturnValue(Address::invalid()),
45*67e74705SXin Li       CapturedStmtInfo(nullptr),
46*67e74705SXin Li       SanOpts(CGM.getLangOpts().Sanitize), IsSanitizerScope(false),
47*67e74705SXin Li       CurFuncIsThunk(false), AutoreleaseResult(false), SawAsmBlock(false),
48*67e74705SXin Li       IsOutlinedSEHHelper(false),
49*67e74705SXin Li       BlockInfo(nullptr), BlockPointer(nullptr),
50*67e74705SXin Li       LambdaThisCaptureField(nullptr), NormalCleanupDest(nullptr),
51*67e74705SXin Li       NextCleanupDestIndex(1), FirstBlockInfo(nullptr), EHResumeBlock(nullptr),
52*67e74705SXin Li       ExceptionSlot(nullptr), EHSelectorSlot(nullptr),
53*67e74705SXin Li       DebugInfo(CGM.getModuleDebugInfo()),
54*67e74705SXin Li       DisableDebugInfo(false), DidCallStackSave(false), IndirectBranch(nullptr),
55*67e74705SXin Li       PGO(cgm), SwitchInsn(nullptr), SwitchWeights(nullptr),
56*67e74705SXin Li       CaseRangeBlock(nullptr), UnreachableBlock(nullptr), NumReturnExprs(0),
57*67e74705SXin Li       NumSimpleReturnExprs(0), CXXABIThisDecl(nullptr),
58*67e74705SXin Li       CXXABIThisValue(nullptr), CXXThisValue(nullptr),
59*67e74705SXin Li       CXXStructorImplicitParamDecl(nullptr),
60*67e74705SXin Li       CXXStructorImplicitParamValue(nullptr), OutermostConditional(nullptr),
61*67e74705SXin Li       CurLexicalScope(nullptr), TerminateLandingPad(nullptr),
62*67e74705SXin Li       TerminateHandler(nullptr), TrapBB(nullptr) {
63*67e74705SXin Li   if (!suppressNewContext)
64*67e74705SXin Li     CGM.getCXXABI().getMangleContext().startNewFunction();
65*67e74705SXin Li 
66*67e74705SXin Li   llvm::FastMathFlags FMF;
67*67e74705SXin Li   if (CGM.getLangOpts().FastMath)
68*67e74705SXin Li     FMF.setUnsafeAlgebra();
69*67e74705SXin Li   if (CGM.getLangOpts().FiniteMathOnly) {
70*67e74705SXin Li     FMF.setNoNaNs();
71*67e74705SXin Li     FMF.setNoInfs();
72*67e74705SXin Li   }
73*67e74705SXin Li   if (CGM.getCodeGenOpts().NoNaNsFPMath) {
74*67e74705SXin Li     FMF.setNoNaNs();
75*67e74705SXin Li   }
76*67e74705SXin Li   if (CGM.getCodeGenOpts().NoSignedZeros) {
77*67e74705SXin Li     FMF.setNoSignedZeros();
78*67e74705SXin Li   }
79*67e74705SXin Li   if (CGM.getCodeGenOpts().ReciprocalMath) {
80*67e74705SXin Li     FMF.setAllowReciprocal();
81*67e74705SXin Li   }
82*67e74705SXin Li   Builder.setFastMathFlags(FMF);
83*67e74705SXin Li }
84*67e74705SXin Li 
~CodeGenFunction()85*67e74705SXin Li CodeGenFunction::~CodeGenFunction() {
86*67e74705SXin Li   assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
87*67e74705SXin Li 
88*67e74705SXin Li   // If there are any unclaimed block infos, go ahead and destroy them
89*67e74705SXin Li   // now.  This can happen if IR-gen gets clever and skips evaluating
90*67e74705SXin Li   // something.
91*67e74705SXin Li   if (FirstBlockInfo)
92*67e74705SXin Li     destroyBlockInfos(FirstBlockInfo);
93*67e74705SXin Li 
94*67e74705SXin Li   if (getLangOpts().OpenMP) {
95*67e74705SXin Li     CGM.getOpenMPRuntime().functionFinished(*this);
96*67e74705SXin Li   }
97*67e74705SXin Li }
98*67e74705SXin Li 
getNaturalPointeeTypeAlignment(QualType T,AlignmentSource * Source)99*67e74705SXin Li CharUnits CodeGenFunction::getNaturalPointeeTypeAlignment(QualType T,
100*67e74705SXin Li                                                      AlignmentSource *Source) {
101*67e74705SXin Li   return getNaturalTypeAlignment(T->getPointeeType(), Source,
102*67e74705SXin Li                                  /*forPointee*/ true);
103*67e74705SXin Li }
104*67e74705SXin Li 
getNaturalTypeAlignment(QualType T,AlignmentSource * Source,bool forPointeeType)105*67e74705SXin Li CharUnits CodeGenFunction::getNaturalTypeAlignment(QualType T,
106*67e74705SXin Li                                                    AlignmentSource *Source,
107*67e74705SXin Li                                                    bool forPointeeType) {
108*67e74705SXin Li   // Honor alignment typedef attributes even on incomplete types.
109*67e74705SXin Li   // We also honor them straight for C++ class types, even as pointees;
110*67e74705SXin Li   // there's an expressivity gap here.
111*67e74705SXin Li   if (auto TT = T->getAs<TypedefType>()) {
112*67e74705SXin Li     if (auto Align = TT->getDecl()->getMaxAlignment()) {
113*67e74705SXin Li       if (Source) *Source = AlignmentSource::AttributedType;
114*67e74705SXin Li       return getContext().toCharUnitsFromBits(Align);
115*67e74705SXin Li     }
116*67e74705SXin Li   }
117*67e74705SXin Li 
118*67e74705SXin Li   if (Source) *Source = AlignmentSource::Type;
119*67e74705SXin Li 
120*67e74705SXin Li   CharUnits Alignment;
121*67e74705SXin Li   if (T->isIncompleteType()) {
122*67e74705SXin Li     Alignment = CharUnits::One(); // Shouldn't be used, but pessimistic is best.
123*67e74705SXin Li   } else {
124*67e74705SXin Li     // For C++ class pointees, we don't know whether we're pointing at a
125*67e74705SXin Li     // base or a complete object, so we generally need to use the
126*67e74705SXin Li     // non-virtual alignment.
127*67e74705SXin Li     const CXXRecordDecl *RD;
128*67e74705SXin Li     if (forPointeeType && (RD = T->getAsCXXRecordDecl())) {
129*67e74705SXin Li       Alignment = CGM.getClassPointerAlignment(RD);
130*67e74705SXin Li     } else {
131*67e74705SXin Li       Alignment = getContext().getTypeAlignInChars(T);
132*67e74705SXin Li     }
133*67e74705SXin Li 
134*67e74705SXin Li     // Cap to the global maximum type alignment unless the alignment
135*67e74705SXin Li     // was somehow explicit on the type.
136*67e74705SXin Li     if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
137*67e74705SXin Li       if (Alignment.getQuantity() > MaxAlign &&
138*67e74705SXin Li           !getContext().isAlignmentRequired(T))
139*67e74705SXin Li         Alignment = CharUnits::fromQuantity(MaxAlign);
140*67e74705SXin Li     }
141*67e74705SXin Li   }
142*67e74705SXin Li   return Alignment;
143*67e74705SXin Li }
144*67e74705SXin Li 
MakeNaturalAlignAddrLValue(llvm::Value * V,QualType T)145*67e74705SXin Li LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
146*67e74705SXin Li   AlignmentSource AlignSource;
147*67e74705SXin Li   CharUnits Alignment = getNaturalTypeAlignment(T, &AlignSource);
148*67e74705SXin Li   return LValue::MakeAddr(Address(V, Alignment), T, getContext(), AlignSource,
149*67e74705SXin Li                           CGM.getTBAAInfo(T));
150*67e74705SXin Li }
151*67e74705SXin Li 
152*67e74705SXin Li /// Given a value of type T* that may not be to a complete object,
153*67e74705SXin Li /// construct an l-value with the natural pointee alignment of T.
154*67e74705SXin Li LValue
MakeNaturalAlignPointeeAddrLValue(llvm::Value * V,QualType T)155*67e74705SXin Li CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
156*67e74705SXin Li   AlignmentSource AlignSource;
157*67e74705SXin Li   CharUnits Align = getNaturalTypeAlignment(T, &AlignSource, /*pointee*/ true);
158*67e74705SXin Li   return MakeAddrLValue(Address(V, Align), T, AlignSource);
159*67e74705SXin Li }
160*67e74705SXin Li 
161*67e74705SXin Li 
ConvertTypeForMem(QualType T)162*67e74705SXin Li llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
163*67e74705SXin Li   return CGM.getTypes().ConvertTypeForMem(T);
164*67e74705SXin Li }
165*67e74705SXin Li 
ConvertType(QualType T)166*67e74705SXin Li llvm::Type *CodeGenFunction::ConvertType(QualType T) {
167*67e74705SXin Li   return CGM.getTypes().ConvertType(T);
168*67e74705SXin Li }
169*67e74705SXin Li 
getEvaluationKind(QualType type)170*67e74705SXin Li TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
171*67e74705SXin Li   type = type.getCanonicalType();
172*67e74705SXin Li   while (true) {
173*67e74705SXin Li     switch (type->getTypeClass()) {
174*67e74705SXin Li #define TYPE(name, parent)
175*67e74705SXin Li #define ABSTRACT_TYPE(name, parent)
176*67e74705SXin Li #define NON_CANONICAL_TYPE(name, parent) case Type::name:
177*67e74705SXin Li #define DEPENDENT_TYPE(name, parent) case Type::name:
178*67e74705SXin Li #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
179*67e74705SXin Li #include "clang/AST/TypeNodes.def"
180*67e74705SXin Li       llvm_unreachable("non-canonical or dependent type in IR-generation");
181*67e74705SXin Li 
182*67e74705SXin Li     case Type::Auto:
183*67e74705SXin Li       llvm_unreachable("undeduced auto type in IR-generation");
184*67e74705SXin Li 
185*67e74705SXin Li     // Various scalar types.
186*67e74705SXin Li     case Type::Builtin:
187*67e74705SXin Li     case Type::Pointer:
188*67e74705SXin Li     case Type::BlockPointer:
189*67e74705SXin Li     case Type::LValueReference:
190*67e74705SXin Li     case Type::RValueReference:
191*67e74705SXin Li     case Type::MemberPointer:
192*67e74705SXin Li     case Type::Vector:
193*67e74705SXin Li     case Type::ExtVector:
194*67e74705SXin Li     case Type::FunctionProto:
195*67e74705SXin Li     case Type::FunctionNoProto:
196*67e74705SXin Li     case Type::Enum:
197*67e74705SXin Li     case Type::ObjCObjectPointer:
198*67e74705SXin Li     case Type::Pipe:
199*67e74705SXin Li       return TEK_Scalar;
200*67e74705SXin Li 
201*67e74705SXin Li     // Complexes.
202*67e74705SXin Li     case Type::Complex:
203*67e74705SXin Li       return TEK_Complex;
204*67e74705SXin Li 
205*67e74705SXin Li     // Arrays, records, and Objective-C objects.
206*67e74705SXin Li     case Type::ConstantArray:
207*67e74705SXin Li     case Type::IncompleteArray:
208*67e74705SXin Li     case Type::VariableArray:
209*67e74705SXin Li     case Type::Record:
210*67e74705SXin Li     case Type::ObjCObject:
211*67e74705SXin Li     case Type::ObjCInterface:
212*67e74705SXin Li       return TEK_Aggregate;
213*67e74705SXin Li 
214*67e74705SXin Li     // We operate on atomic values according to their underlying type.
215*67e74705SXin Li     case Type::Atomic:
216*67e74705SXin Li       type = cast<AtomicType>(type)->getValueType();
217*67e74705SXin Li       continue;
218*67e74705SXin Li     }
219*67e74705SXin Li     llvm_unreachable("unknown type kind!");
220*67e74705SXin Li   }
221*67e74705SXin Li }
222*67e74705SXin Li 
EmitReturnBlock()223*67e74705SXin Li llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
224*67e74705SXin Li   // For cleanliness, we try to avoid emitting the return block for
225*67e74705SXin Li   // simple cases.
226*67e74705SXin Li   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
227*67e74705SXin Li 
228*67e74705SXin Li   if (CurBB) {
229*67e74705SXin Li     assert(!CurBB->getTerminator() && "Unexpected terminated block.");
230*67e74705SXin Li 
231*67e74705SXin Li     // We have a valid insert point, reuse it if it is empty or there are no
232*67e74705SXin Li     // explicit jumps to the return block.
233*67e74705SXin Li     if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
234*67e74705SXin Li       ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
235*67e74705SXin Li       delete ReturnBlock.getBlock();
236*67e74705SXin Li     } else
237*67e74705SXin Li       EmitBlock(ReturnBlock.getBlock());
238*67e74705SXin Li     return llvm::DebugLoc();
239*67e74705SXin Li   }
240*67e74705SXin Li 
241*67e74705SXin Li   // Otherwise, if the return block is the target of a single direct
242*67e74705SXin Li   // branch then we can just put the code in that block instead. This
243*67e74705SXin Li   // cleans up functions which started with a unified return block.
244*67e74705SXin Li   if (ReturnBlock.getBlock()->hasOneUse()) {
245*67e74705SXin Li     llvm::BranchInst *BI =
246*67e74705SXin Li       dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
247*67e74705SXin Li     if (BI && BI->isUnconditional() &&
248*67e74705SXin Li         BI->getSuccessor(0) == ReturnBlock.getBlock()) {
249*67e74705SXin Li       // Record/return the DebugLoc of the simple 'return' expression to be used
250*67e74705SXin Li       // later by the actual 'ret' instruction.
251*67e74705SXin Li       llvm::DebugLoc Loc = BI->getDebugLoc();
252*67e74705SXin Li       Builder.SetInsertPoint(BI->getParent());
253*67e74705SXin Li       BI->eraseFromParent();
254*67e74705SXin Li       delete ReturnBlock.getBlock();
255*67e74705SXin Li       return Loc;
256*67e74705SXin Li     }
257*67e74705SXin Li   }
258*67e74705SXin Li 
259*67e74705SXin Li   // FIXME: We are at an unreachable point, there is no reason to emit the block
260*67e74705SXin Li   // unless it has uses. However, we still need a place to put the debug
261*67e74705SXin Li   // region.end for now.
262*67e74705SXin Li 
263*67e74705SXin Li   EmitBlock(ReturnBlock.getBlock());
264*67e74705SXin Li   return llvm::DebugLoc();
265*67e74705SXin Li }
266*67e74705SXin Li 
EmitIfUsed(CodeGenFunction & CGF,llvm::BasicBlock * BB)267*67e74705SXin Li static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
268*67e74705SXin Li   if (!BB) return;
269*67e74705SXin Li   if (!BB->use_empty())
270*67e74705SXin Li     return CGF.CurFn->getBasicBlockList().push_back(BB);
271*67e74705SXin Li   delete BB;
272*67e74705SXin Li }
273*67e74705SXin Li 
FinishFunction(SourceLocation EndLoc)274*67e74705SXin Li void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
275*67e74705SXin Li   assert(BreakContinueStack.empty() &&
276*67e74705SXin Li          "mismatched push/pop in break/continue stack!");
277*67e74705SXin Li 
278*67e74705SXin Li   bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
279*67e74705SXin Li     && NumSimpleReturnExprs == NumReturnExprs
280*67e74705SXin Li     && ReturnBlock.getBlock()->use_empty();
281*67e74705SXin Li   // Usually the return expression is evaluated before the cleanup
282*67e74705SXin Li   // code.  If the function contains only a simple return statement,
283*67e74705SXin Li   // such as a constant, the location before the cleanup code becomes
284*67e74705SXin Li   // the last useful breakpoint in the function, because the simple
285*67e74705SXin Li   // return expression will be evaluated after the cleanup code. To be
286*67e74705SXin Li   // safe, set the debug location for cleanup code to the location of
287*67e74705SXin Li   // the return statement.  Otherwise the cleanup code should be at the
288*67e74705SXin Li   // end of the function's lexical scope.
289*67e74705SXin Li   //
290*67e74705SXin Li   // If there are multiple branches to the return block, the branch
291*67e74705SXin Li   // instructions will get the location of the return statements and
292*67e74705SXin Li   // all will be fine.
293*67e74705SXin Li   if (CGDebugInfo *DI = getDebugInfo()) {
294*67e74705SXin Li     if (OnlySimpleReturnStmts)
295*67e74705SXin Li       DI->EmitLocation(Builder, LastStopPoint);
296*67e74705SXin Li     else
297*67e74705SXin Li       DI->EmitLocation(Builder, EndLoc);
298*67e74705SXin Li   }
299*67e74705SXin Li 
300*67e74705SXin Li   // Pop any cleanups that might have been associated with the
301*67e74705SXin Li   // parameters.  Do this in whatever block we're currently in; it's
302*67e74705SXin Li   // important to do this before we enter the return block or return
303*67e74705SXin Li   // edges will be *really* confused.
304*67e74705SXin Li   bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
305*67e74705SXin Li   bool HasOnlyLifetimeMarkers =
306*67e74705SXin Li       HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth);
307*67e74705SXin Li   bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
308*67e74705SXin Li   if (HasCleanups) {
309*67e74705SXin Li     // Make sure the line table doesn't jump back into the body for
310*67e74705SXin Li     // the ret after it's been at EndLoc.
311*67e74705SXin Li     if (CGDebugInfo *DI = getDebugInfo())
312*67e74705SXin Li       if (OnlySimpleReturnStmts)
313*67e74705SXin Li         DI->EmitLocation(Builder, EndLoc);
314*67e74705SXin Li 
315*67e74705SXin Li     PopCleanupBlocks(PrologueCleanupDepth);
316*67e74705SXin Li   }
317*67e74705SXin Li 
318*67e74705SXin Li   // Emit function epilog (to return).
319*67e74705SXin Li   llvm::DebugLoc Loc = EmitReturnBlock();
320*67e74705SXin Li 
321*67e74705SXin Li   if (ShouldInstrumentFunction())
322*67e74705SXin Li     EmitFunctionInstrumentation("__cyg_profile_func_exit");
323*67e74705SXin Li 
324*67e74705SXin Li   // Emit debug descriptor for function end.
325*67e74705SXin Li   if (CGDebugInfo *DI = getDebugInfo())
326*67e74705SXin Li     DI->EmitFunctionEnd(Builder);
327*67e74705SXin Li 
328*67e74705SXin Li   // Reset the debug location to that of the simple 'return' expression, if any
329*67e74705SXin Li   // rather than that of the end of the function's scope '}'.
330*67e74705SXin Li   ApplyDebugLocation AL(*this, Loc);
331*67e74705SXin Li   EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
332*67e74705SXin Li   EmitEndEHSpec(CurCodeDecl);
333*67e74705SXin Li 
334*67e74705SXin Li   assert(EHStack.empty() &&
335*67e74705SXin Li          "did not remove all scopes from cleanup stack!");
336*67e74705SXin Li 
337*67e74705SXin Li   // If someone did an indirect goto, emit the indirect goto block at the end of
338*67e74705SXin Li   // the function.
339*67e74705SXin Li   if (IndirectBranch) {
340*67e74705SXin Li     EmitBlock(IndirectBranch->getParent());
341*67e74705SXin Li     Builder.ClearInsertionPoint();
342*67e74705SXin Li   }
343*67e74705SXin Li 
344*67e74705SXin Li   // If some of our locals escaped, insert a call to llvm.localescape in the
345*67e74705SXin Li   // entry block.
346*67e74705SXin Li   if (!EscapedLocals.empty()) {
347*67e74705SXin Li     // Invert the map from local to index into a simple vector. There should be
348*67e74705SXin Li     // no holes.
349*67e74705SXin Li     SmallVector<llvm::Value *, 4> EscapeArgs;
350*67e74705SXin Li     EscapeArgs.resize(EscapedLocals.size());
351*67e74705SXin Li     for (auto &Pair : EscapedLocals)
352*67e74705SXin Li       EscapeArgs[Pair.second] = Pair.first;
353*67e74705SXin Li     llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
354*67e74705SXin Li         &CGM.getModule(), llvm::Intrinsic::localescape);
355*67e74705SXin Li     CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
356*67e74705SXin Li   }
357*67e74705SXin Li 
358*67e74705SXin Li   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
359*67e74705SXin Li   llvm::Instruction *Ptr = AllocaInsertPt;
360*67e74705SXin Li   AllocaInsertPt = nullptr;
361*67e74705SXin Li   Ptr->eraseFromParent();
362*67e74705SXin Li 
363*67e74705SXin Li   // If someone took the address of a label but never did an indirect goto, we
364*67e74705SXin Li   // made a zero entry PHI node, which is illegal, zap it now.
365*67e74705SXin Li   if (IndirectBranch) {
366*67e74705SXin Li     llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
367*67e74705SXin Li     if (PN->getNumIncomingValues() == 0) {
368*67e74705SXin Li       PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
369*67e74705SXin Li       PN->eraseFromParent();
370*67e74705SXin Li     }
371*67e74705SXin Li   }
372*67e74705SXin Li 
373*67e74705SXin Li   EmitIfUsed(*this, EHResumeBlock);
374*67e74705SXin Li   EmitIfUsed(*this, TerminateLandingPad);
375*67e74705SXin Li   EmitIfUsed(*this, TerminateHandler);
376*67e74705SXin Li   EmitIfUsed(*this, UnreachableBlock);
377*67e74705SXin Li 
378*67e74705SXin Li   if (CGM.getCodeGenOpts().EmitDeclMetadata)
379*67e74705SXin Li     EmitDeclMetadata();
380*67e74705SXin Li 
381*67e74705SXin Li   for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
382*67e74705SXin Li            I = DeferredReplacements.begin(),
383*67e74705SXin Li            E = DeferredReplacements.end();
384*67e74705SXin Li        I != E; ++I) {
385*67e74705SXin Li     I->first->replaceAllUsesWith(I->second);
386*67e74705SXin Li     I->first->eraseFromParent();
387*67e74705SXin Li   }
388*67e74705SXin Li }
389*67e74705SXin Li 
390*67e74705SXin Li /// ShouldInstrumentFunction - Return true if the current function should be
391*67e74705SXin Li /// instrumented with __cyg_profile_func_* calls
ShouldInstrumentFunction()392*67e74705SXin Li bool CodeGenFunction::ShouldInstrumentFunction() {
393*67e74705SXin Li   if (!CGM.getCodeGenOpts().InstrumentFunctions)
394*67e74705SXin Li     return false;
395*67e74705SXin Li   if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
396*67e74705SXin Li     return false;
397*67e74705SXin Li   return true;
398*67e74705SXin Li }
399*67e74705SXin Li 
400*67e74705SXin Li /// ShouldXRayInstrument - Return true if the current function should be
401*67e74705SXin Li /// instrumented with XRay nop sleds.
ShouldXRayInstrumentFunction() const402*67e74705SXin Li bool CodeGenFunction::ShouldXRayInstrumentFunction() const {
403*67e74705SXin Li   return CGM.getCodeGenOpts().XRayInstrumentFunctions;
404*67e74705SXin Li }
405*67e74705SXin Li 
406*67e74705SXin Li /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
407*67e74705SXin Li /// instrumentation function with the current function and the call site, if
408*67e74705SXin Li /// function instrumentation is enabled.
EmitFunctionInstrumentation(const char * Fn)409*67e74705SXin Li void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
410*67e74705SXin Li   auto NL = ApplyDebugLocation::CreateArtificial(*this);
411*67e74705SXin Li   // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
412*67e74705SXin Li   llvm::PointerType *PointerTy = Int8PtrTy;
413*67e74705SXin Li   llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy };
414*67e74705SXin Li   llvm::FunctionType *FunctionTy =
415*67e74705SXin Li     llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false);
416*67e74705SXin Li 
417*67e74705SXin Li   llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
418*67e74705SXin Li   llvm::CallInst *CallSite = Builder.CreateCall(
419*67e74705SXin Li     CGM.getIntrinsic(llvm::Intrinsic::returnaddress),
420*67e74705SXin Li     llvm::ConstantInt::get(Int32Ty, 0),
421*67e74705SXin Li     "callsite");
422*67e74705SXin Li 
423*67e74705SXin Li   llvm::Value *args[] = {
424*67e74705SXin Li     llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
425*67e74705SXin Li     CallSite
426*67e74705SXin Li   };
427*67e74705SXin Li 
428*67e74705SXin Li   EmitNounwindRuntimeCall(F, args);
429*67e74705SXin Li }
430*67e74705SXin Li 
EmitMCountInstrumentation()431*67e74705SXin Li void CodeGenFunction::EmitMCountInstrumentation() {
432*67e74705SXin Li   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
433*67e74705SXin Li 
434*67e74705SXin Li   llvm::Constant *MCountFn =
435*67e74705SXin Li     CGM.CreateRuntimeFunction(FTy, getTarget().getMCountName());
436*67e74705SXin Li   EmitNounwindRuntimeCall(MCountFn);
437*67e74705SXin Li }
438*67e74705SXin Li 
439*67e74705SXin Li // OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
440*67e74705SXin Li // information in the program executable. The argument information stored
441*67e74705SXin Li // includes the argument name, its type, the address and access qualifiers used.
GenOpenCLArgMetadata(const FunctionDecl * FD,llvm::Function * Fn,CodeGenModule & CGM,llvm::LLVMContext & Context,CGBuilderTy & Builder,ASTContext & ASTCtx)442*67e74705SXin Li static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn,
443*67e74705SXin Li                                  CodeGenModule &CGM, llvm::LLVMContext &Context,
444*67e74705SXin Li                                  CGBuilderTy &Builder, ASTContext &ASTCtx) {
445*67e74705SXin Li   // Create MDNodes that represent the kernel arg metadata.
446*67e74705SXin Li   // Each MDNode is a list in the form of "key", N number of values which is
447*67e74705SXin Li   // the same number of values as their are kernel arguments.
448*67e74705SXin Li 
449*67e74705SXin Li   const PrintingPolicy &Policy = ASTCtx.getPrintingPolicy();
450*67e74705SXin Li 
451*67e74705SXin Li   // MDNode for the kernel argument address space qualifiers.
452*67e74705SXin Li   SmallVector<llvm::Metadata *, 8> addressQuals;
453*67e74705SXin Li 
454*67e74705SXin Li   // MDNode for the kernel argument access qualifiers (images only).
455*67e74705SXin Li   SmallVector<llvm::Metadata *, 8> accessQuals;
456*67e74705SXin Li 
457*67e74705SXin Li   // MDNode for the kernel argument type names.
458*67e74705SXin Li   SmallVector<llvm::Metadata *, 8> argTypeNames;
459*67e74705SXin Li 
460*67e74705SXin Li   // MDNode for the kernel argument base type names.
461*67e74705SXin Li   SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
462*67e74705SXin Li 
463*67e74705SXin Li   // MDNode for the kernel argument type qualifiers.
464*67e74705SXin Li   SmallVector<llvm::Metadata *, 8> argTypeQuals;
465*67e74705SXin Li 
466*67e74705SXin Li   // MDNode for the kernel argument names.
467*67e74705SXin Li   SmallVector<llvm::Metadata *, 8> argNames;
468*67e74705SXin Li 
469*67e74705SXin Li   for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
470*67e74705SXin Li     const ParmVarDecl *parm = FD->getParamDecl(i);
471*67e74705SXin Li     QualType ty = parm->getType();
472*67e74705SXin Li     std::string typeQuals;
473*67e74705SXin Li 
474*67e74705SXin Li     if (ty->isPointerType()) {
475*67e74705SXin Li       QualType pointeeTy = ty->getPointeeType();
476*67e74705SXin Li 
477*67e74705SXin Li       // Get address qualifier.
478*67e74705SXin Li       addressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(
479*67e74705SXin Li           ASTCtx.getTargetAddressSpace(pointeeTy.getAddressSpace()))));
480*67e74705SXin Li 
481*67e74705SXin Li       // Get argument type name.
482*67e74705SXin Li       std::string typeName =
483*67e74705SXin Li           pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
484*67e74705SXin Li 
485*67e74705SXin Li       // Turn "unsigned type" to "utype"
486*67e74705SXin Li       std::string::size_type pos = typeName.find("unsigned");
487*67e74705SXin Li       if (pointeeTy.isCanonical() && pos != std::string::npos)
488*67e74705SXin Li         typeName.erase(pos+1, 8);
489*67e74705SXin Li 
490*67e74705SXin Li       argTypeNames.push_back(llvm::MDString::get(Context, typeName));
491*67e74705SXin Li 
492*67e74705SXin Li       std::string baseTypeName =
493*67e74705SXin Li           pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
494*67e74705SXin Li               Policy) +
495*67e74705SXin Li           "*";
496*67e74705SXin Li 
497*67e74705SXin Li       // Turn "unsigned type" to "utype"
498*67e74705SXin Li       pos = baseTypeName.find("unsigned");
499*67e74705SXin Li       if (pos != std::string::npos)
500*67e74705SXin Li         baseTypeName.erase(pos+1, 8);
501*67e74705SXin Li 
502*67e74705SXin Li       argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
503*67e74705SXin Li 
504*67e74705SXin Li       // Get argument type qualifiers:
505*67e74705SXin Li       if (ty.isRestrictQualified())
506*67e74705SXin Li         typeQuals = "restrict";
507*67e74705SXin Li       if (pointeeTy.isConstQualified() ||
508*67e74705SXin Li           (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
509*67e74705SXin Li         typeQuals += typeQuals.empty() ? "const" : " const";
510*67e74705SXin Li       if (pointeeTy.isVolatileQualified())
511*67e74705SXin Li         typeQuals += typeQuals.empty() ? "volatile" : " volatile";
512*67e74705SXin Li     } else {
513*67e74705SXin Li       uint32_t AddrSpc = 0;
514*67e74705SXin Li       bool isPipe = ty->isPipeType();
515*67e74705SXin Li       if (ty->isImageType() || isPipe)
516*67e74705SXin Li         AddrSpc =
517*67e74705SXin Li           CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
518*67e74705SXin Li 
519*67e74705SXin Li       addressQuals.push_back(
520*67e74705SXin Li           llvm::ConstantAsMetadata::get(Builder.getInt32(AddrSpc)));
521*67e74705SXin Li 
522*67e74705SXin Li       // Get argument type name.
523*67e74705SXin Li       std::string typeName;
524*67e74705SXin Li       if (isPipe)
525*67e74705SXin Li         typeName = ty.getCanonicalType()->getAs<PipeType>()->getElementType()
526*67e74705SXin Li                      .getAsString(Policy);
527*67e74705SXin Li       else
528*67e74705SXin Li         typeName = ty.getUnqualifiedType().getAsString(Policy);
529*67e74705SXin Li 
530*67e74705SXin Li       // Turn "unsigned type" to "utype"
531*67e74705SXin Li       std::string::size_type pos = typeName.find("unsigned");
532*67e74705SXin Li       if (ty.isCanonical() && pos != std::string::npos)
533*67e74705SXin Li         typeName.erase(pos+1, 8);
534*67e74705SXin Li 
535*67e74705SXin Li       argTypeNames.push_back(llvm::MDString::get(Context, typeName));
536*67e74705SXin Li 
537*67e74705SXin Li       std::string baseTypeName;
538*67e74705SXin Li       if (isPipe)
539*67e74705SXin Li         baseTypeName = ty.getCanonicalType()->getAs<PipeType>()
540*67e74705SXin Li                           ->getElementType().getCanonicalType()
541*67e74705SXin Li                           .getAsString(Policy);
542*67e74705SXin Li       else
543*67e74705SXin Li         baseTypeName =
544*67e74705SXin Li           ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
545*67e74705SXin Li 
546*67e74705SXin Li       // Turn "unsigned type" to "utype"
547*67e74705SXin Li       pos = baseTypeName.find("unsigned");
548*67e74705SXin Li       if (pos != std::string::npos)
549*67e74705SXin Li         baseTypeName.erase(pos+1, 8);
550*67e74705SXin Li 
551*67e74705SXin Li       argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
552*67e74705SXin Li 
553*67e74705SXin Li       // Get argument type qualifiers:
554*67e74705SXin Li       if (ty.isConstQualified())
555*67e74705SXin Li         typeQuals = "const";
556*67e74705SXin Li       if (ty.isVolatileQualified())
557*67e74705SXin Li         typeQuals += typeQuals.empty() ? "volatile" : " volatile";
558*67e74705SXin Li       if (isPipe)
559*67e74705SXin Li         typeQuals = "pipe";
560*67e74705SXin Li     }
561*67e74705SXin Li 
562*67e74705SXin Li     argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals));
563*67e74705SXin Li 
564*67e74705SXin Li     // Get image and pipe access qualifier:
565*67e74705SXin Li     if (ty->isImageType()|| ty->isPipeType()) {
566*67e74705SXin Li       const OpenCLAccessAttr *A = parm->getAttr<OpenCLAccessAttr>();
567*67e74705SXin Li       if (A && A->isWriteOnly())
568*67e74705SXin Li         accessQuals.push_back(llvm::MDString::get(Context, "write_only"));
569*67e74705SXin Li       else if (A && A->isReadWrite())
570*67e74705SXin Li         accessQuals.push_back(llvm::MDString::get(Context, "read_write"));
571*67e74705SXin Li       else
572*67e74705SXin Li         accessQuals.push_back(llvm::MDString::get(Context, "read_only"));
573*67e74705SXin Li     } else
574*67e74705SXin Li       accessQuals.push_back(llvm::MDString::get(Context, "none"));
575*67e74705SXin Li 
576*67e74705SXin Li     // Get argument name.
577*67e74705SXin Li     argNames.push_back(llvm::MDString::get(Context, parm->getName()));
578*67e74705SXin Li   }
579*67e74705SXin Li 
580*67e74705SXin Li   Fn->setMetadata("kernel_arg_addr_space",
581*67e74705SXin Li                   llvm::MDNode::get(Context, addressQuals));
582*67e74705SXin Li   Fn->setMetadata("kernel_arg_access_qual",
583*67e74705SXin Li                   llvm::MDNode::get(Context, accessQuals));
584*67e74705SXin Li   Fn->setMetadata("kernel_arg_type",
585*67e74705SXin Li                   llvm::MDNode::get(Context, argTypeNames));
586*67e74705SXin Li   Fn->setMetadata("kernel_arg_base_type",
587*67e74705SXin Li                   llvm::MDNode::get(Context, argBaseTypeNames));
588*67e74705SXin Li   Fn->setMetadata("kernel_arg_type_qual",
589*67e74705SXin Li                   llvm::MDNode::get(Context, argTypeQuals));
590*67e74705SXin Li   if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
591*67e74705SXin Li     Fn->setMetadata("kernel_arg_name",
592*67e74705SXin Li                     llvm::MDNode::get(Context, argNames));
593*67e74705SXin Li }
594*67e74705SXin Li 
EmitOpenCLKernelMetadata(const FunctionDecl * FD,llvm::Function * Fn)595*67e74705SXin Li void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
596*67e74705SXin Li                                                llvm::Function *Fn)
597*67e74705SXin Li {
598*67e74705SXin Li   if (!FD->hasAttr<OpenCLKernelAttr>())
599*67e74705SXin Li     return;
600*67e74705SXin Li 
601*67e74705SXin Li   llvm::LLVMContext &Context = getLLVMContext();
602*67e74705SXin Li 
603*67e74705SXin Li   GenOpenCLArgMetadata(FD, Fn, CGM, Context, Builder, getContext());
604*67e74705SXin Li 
605*67e74705SXin Li   if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
606*67e74705SXin Li     QualType hintQTy = A->getTypeHint();
607*67e74705SXin Li     const ExtVectorType *hintEltQTy = hintQTy->getAs<ExtVectorType>();
608*67e74705SXin Li     bool isSignedInteger =
609*67e74705SXin Li         hintQTy->isSignedIntegerType() ||
610*67e74705SXin Li         (hintEltQTy && hintEltQTy->getElementType()->isSignedIntegerType());
611*67e74705SXin Li     llvm::Metadata *attrMDArgs[] = {
612*67e74705SXin Li         llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
613*67e74705SXin Li             CGM.getTypes().ConvertType(A->getTypeHint()))),
614*67e74705SXin Li         llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
615*67e74705SXin Li             llvm::IntegerType::get(Context, 32),
616*67e74705SXin Li             llvm::APInt(32, (uint64_t)(isSignedInteger ? 1 : 0))))};
617*67e74705SXin Li     Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, attrMDArgs));
618*67e74705SXin Li   }
619*67e74705SXin Li 
620*67e74705SXin Li   if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
621*67e74705SXin Li     llvm::Metadata *attrMDArgs[] = {
622*67e74705SXin Li         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
623*67e74705SXin Li         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
624*67e74705SXin Li         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
625*67e74705SXin Li     Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, attrMDArgs));
626*67e74705SXin Li   }
627*67e74705SXin Li 
628*67e74705SXin Li   if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
629*67e74705SXin Li     llvm::Metadata *attrMDArgs[] = {
630*67e74705SXin Li         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
631*67e74705SXin Li         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
632*67e74705SXin Li         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
633*67e74705SXin Li     Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, attrMDArgs));
634*67e74705SXin Li   }
635*67e74705SXin Li }
636*67e74705SXin Li 
637*67e74705SXin Li /// Determine whether the function F ends with a return stmt.
endsWithReturn(const Decl * F)638*67e74705SXin Li static bool endsWithReturn(const Decl* F) {
639*67e74705SXin Li   const Stmt *Body = nullptr;
640*67e74705SXin Li   if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
641*67e74705SXin Li     Body = FD->getBody();
642*67e74705SXin Li   else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
643*67e74705SXin Li     Body = OMD->getBody();
644*67e74705SXin Li 
645*67e74705SXin Li   if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
646*67e74705SXin Li     auto LastStmt = CS->body_rbegin();
647*67e74705SXin Li     if (LastStmt != CS->body_rend())
648*67e74705SXin Li       return isa<ReturnStmt>(*LastStmt);
649*67e74705SXin Li   }
650*67e74705SXin Li   return false;
651*67e74705SXin Li }
652*67e74705SXin Li 
StartFunction(GlobalDecl GD,QualType RetTy,llvm::Function * Fn,const CGFunctionInfo & FnInfo,const FunctionArgList & Args,SourceLocation Loc,SourceLocation StartLoc)653*67e74705SXin Li void CodeGenFunction::StartFunction(GlobalDecl GD,
654*67e74705SXin Li                                     QualType RetTy,
655*67e74705SXin Li                                     llvm::Function *Fn,
656*67e74705SXin Li                                     const CGFunctionInfo &FnInfo,
657*67e74705SXin Li                                     const FunctionArgList &Args,
658*67e74705SXin Li                                     SourceLocation Loc,
659*67e74705SXin Li                                     SourceLocation StartLoc) {
660*67e74705SXin Li   assert(!CurFn &&
661*67e74705SXin Li          "Do not use a CodeGenFunction object for more than one function");
662*67e74705SXin Li 
663*67e74705SXin Li   const Decl *D = GD.getDecl();
664*67e74705SXin Li 
665*67e74705SXin Li   DidCallStackSave = false;
666*67e74705SXin Li   CurCodeDecl = D;
667*67e74705SXin Li   if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D))
668*67e74705SXin Li     if (FD->usesSEHTry())
669*67e74705SXin Li       CurSEHParent = FD;
670*67e74705SXin Li   CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
671*67e74705SXin Li   FnRetTy = RetTy;
672*67e74705SXin Li   CurFn = Fn;
673*67e74705SXin Li   CurFnInfo = &FnInfo;
674*67e74705SXin Li   assert(CurFn->isDeclaration() && "Function already has body?");
675*67e74705SXin Li 
676*67e74705SXin Li   if (CGM.isInSanitizerBlacklist(Fn, Loc))
677*67e74705SXin Li     SanOpts.clear();
678*67e74705SXin Li 
679*67e74705SXin Li   if (D) {
680*67e74705SXin Li     // Apply the no_sanitize* attributes to SanOpts.
681*67e74705SXin Li     for (auto Attr : D->specific_attrs<NoSanitizeAttr>())
682*67e74705SXin Li       SanOpts.Mask &= ~Attr->getMask();
683*67e74705SXin Li   }
684*67e74705SXin Li 
685*67e74705SXin Li   // Apply sanitizer attributes to the function.
686*67e74705SXin Li   if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
687*67e74705SXin Li     Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
688*67e74705SXin Li   if (SanOpts.has(SanitizerKind::Thread))
689*67e74705SXin Li     Fn->addFnAttr(llvm::Attribute::SanitizeThread);
690*67e74705SXin Li   if (SanOpts.has(SanitizerKind::Memory))
691*67e74705SXin Li     Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
692*67e74705SXin Li   if (SanOpts.has(SanitizerKind::SafeStack))
693*67e74705SXin Li     Fn->addFnAttr(llvm::Attribute::SafeStack);
694*67e74705SXin Li 
695*67e74705SXin Li   // Apply xray attributes to the function (as a string, for now)
696*67e74705SXin Li   if (D && ShouldXRayInstrumentFunction()) {
697*67e74705SXin Li     if (const auto *XRayAttr = D->getAttr<XRayInstrumentAttr>()) {
698*67e74705SXin Li       if (XRayAttr->alwaysXRayInstrument())
699*67e74705SXin Li         Fn->addFnAttr("function-instrument", "xray-always");
700*67e74705SXin Li       if (XRayAttr->neverXRayInstrument())
701*67e74705SXin Li         Fn->addFnAttr("function-instrument", "xray-never");
702*67e74705SXin Li     } else {
703*67e74705SXin Li       Fn->addFnAttr(
704*67e74705SXin Li           "xray-instruction-threshold",
705*67e74705SXin Li           llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
706*67e74705SXin Li     }
707*67e74705SXin Li   }
708*67e74705SXin Li 
709*67e74705SXin Li   // Pass inline keyword to optimizer if it appears explicitly on any
710*67e74705SXin Li   // declaration. Also, in the case of -fno-inline attach NoInline
711*67e74705SXin Li   // attribute to all functions that are not marked AlwaysInline, or
712*67e74705SXin Li   // to all functions that are not marked inline or implicitly inline
713*67e74705SXin Li   // in the case of -finline-hint-functions.
714*67e74705SXin Li   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
715*67e74705SXin Li     const CodeGenOptions& CodeGenOpts = CGM.getCodeGenOpts();
716*67e74705SXin Li     if (!CodeGenOpts.NoInline) {
717*67e74705SXin Li       for (auto RI : FD->redecls())
718*67e74705SXin Li         if (RI->isInlineSpecified()) {
719*67e74705SXin Li           Fn->addFnAttr(llvm::Attribute::InlineHint);
720*67e74705SXin Li           break;
721*67e74705SXin Li         }
722*67e74705SXin Li       if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyHintInlining &&
723*67e74705SXin Li           !FD->isInlined() && !Fn->hasFnAttribute(llvm::Attribute::InlineHint))
724*67e74705SXin Li         Fn->addFnAttr(llvm::Attribute::NoInline);
725*67e74705SXin Li     } else if (!FD->hasAttr<AlwaysInlineAttr>())
726*67e74705SXin Li       Fn->addFnAttr(llvm::Attribute::NoInline);
727*67e74705SXin Li     if (CGM.getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
728*67e74705SXin Li       CGM.getOpenMPRuntime().emitDeclareSimdFunction(FD, Fn);
729*67e74705SXin Li   }
730*67e74705SXin Li 
731*67e74705SXin Li   // Add no-jump-tables value.
732*67e74705SXin Li   Fn->addFnAttr("no-jump-tables",
733*67e74705SXin Li                 llvm::toStringRef(CGM.getCodeGenOpts().NoUseJumpTables));
734*67e74705SXin Li 
735*67e74705SXin Li   if (getLangOpts().OpenCL) {
736*67e74705SXin Li     // Add metadata for a kernel function.
737*67e74705SXin Li     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
738*67e74705SXin Li       EmitOpenCLKernelMetadata(FD, Fn);
739*67e74705SXin Li   }
740*67e74705SXin Li 
741*67e74705SXin Li   // If we are checking function types, emit a function type signature as
742*67e74705SXin Li   // prologue data.
743*67e74705SXin Li   if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
744*67e74705SXin Li     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
745*67e74705SXin Li       if (llvm::Constant *PrologueSig =
746*67e74705SXin Li               CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
747*67e74705SXin Li         llvm::Constant *FTRTTIConst =
748*67e74705SXin Li             CGM.GetAddrOfRTTIDescriptor(FD->getType(), /*ForEH=*/true);
749*67e74705SXin Li         llvm::Constant *PrologueStructElems[] = { PrologueSig, FTRTTIConst };
750*67e74705SXin Li         llvm::Constant *PrologueStructConst =
751*67e74705SXin Li             llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
752*67e74705SXin Li         Fn->setPrologueData(PrologueStructConst);
753*67e74705SXin Li       }
754*67e74705SXin Li     }
755*67e74705SXin Li   }
756*67e74705SXin Li 
757*67e74705SXin Li   // If we're in C++ mode and the function name is "main", it is guaranteed
758*67e74705SXin Li   // to be norecurse by the standard (3.6.1.3 "The function main shall not be
759*67e74705SXin Li   // used within a program").
760*67e74705SXin Li   if (getLangOpts().CPlusPlus)
761*67e74705SXin Li     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
762*67e74705SXin Li       if (FD->isMain())
763*67e74705SXin Li         Fn->addFnAttr(llvm::Attribute::NoRecurse);
764*67e74705SXin Li 
765*67e74705SXin Li   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
766*67e74705SXin Li 
767*67e74705SXin Li   // Create a marker to make it easy to insert allocas into the entryblock
768*67e74705SXin Li   // later.  Don't create this with the builder, because we don't want it
769*67e74705SXin Li   // folded.
770*67e74705SXin Li   llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
771*67e74705SXin Li   AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB);
772*67e74705SXin Li 
773*67e74705SXin Li   ReturnBlock = getJumpDestInCurrentScope("return");
774*67e74705SXin Li 
775*67e74705SXin Li   Builder.SetInsertPoint(EntryBB);
776*67e74705SXin Li 
777*67e74705SXin Li   // Emit subprogram debug descriptor.
778*67e74705SXin Li   if (CGDebugInfo *DI = getDebugInfo()) {
779*67e74705SXin Li     // Reconstruct the type from the argument list so that implicit parameters,
780*67e74705SXin Li     // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
781*67e74705SXin Li     // convention.
782*67e74705SXin Li     CallingConv CC = CallingConv::CC_C;
783*67e74705SXin Li     if (auto *FD = dyn_cast_or_null<FunctionDecl>(D))
784*67e74705SXin Li       if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
785*67e74705SXin Li         CC = SrcFnTy->getCallConv();
786*67e74705SXin Li     SmallVector<QualType, 16> ArgTypes;
787*67e74705SXin Li     for (const VarDecl *VD : Args)
788*67e74705SXin Li       ArgTypes.push_back(VD->getType());
789*67e74705SXin Li     QualType FnType = getContext().getFunctionType(
790*67e74705SXin Li         RetTy, ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
791*67e74705SXin Li     DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, Builder);
792*67e74705SXin Li   }
793*67e74705SXin Li 
794*67e74705SXin Li   if (ShouldInstrumentFunction())
795*67e74705SXin Li     EmitFunctionInstrumentation("__cyg_profile_func_enter");
796*67e74705SXin Li 
797*67e74705SXin Li   if (CGM.getCodeGenOpts().InstrumentForProfiling)
798*67e74705SXin Li     EmitMCountInstrumentation();
799*67e74705SXin Li 
800*67e74705SXin Li   if (RetTy->isVoidType()) {
801*67e74705SXin Li     // Void type; nothing to return.
802*67e74705SXin Li     ReturnValue = Address::invalid();
803*67e74705SXin Li 
804*67e74705SXin Li     // Count the implicit return.
805*67e74705SXin Li     if (!endsWithReturn(D))
806*67e74705SXin Li       ++NumReturnExprs;
807*67e74705SXin Li   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
808*67e74705SXin Li              !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
809*67e74705SXin Li     // Indirect aggregate return; emit returned value directly into sret slot.
810*67e74705SXin Li     // This reduces code size, and affects correctness in C++.
811*67e74705SXin Li     auto AI = CurFn->arg_begin();
812*67e74705SXin Li     if (CurFnInfo->getReturnInfo().isSRetAfterThis())
813*67e74705SXin Li       ++AI;
814*67e74705SXin Li     ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign());
815*67e74705SXin Li   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
816*67e74705SXin Li              !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
817*67e74705SXin Li     // Load the sret pointer from the argument struct and return into that.
818*67e74705SXin Li     unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
819*67e74705SXin Li     llvm::Function::arg_iterator EI = CurFn->arg_end();
820*67e74705SXin Li     --EI;
821*67e74705SXin Li     llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx);
822*67e74705SXin Li     Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result");
823*67e74705SXin Li     ReturnValue = Address(Addr, getNaturalTypeAlignment(RetTy));
824*67e74705SXin Li   } else {
825*67e74705SXin Li     ReturnValue = CreateIRTemp(RetTy, "retval");
826*67e74705SXin Li 
827*67e74705SXin Li     // Tell the epilog emitter to autorelease the result.  We do this
828*67e74705SXin Li     // now so that various specialized functions can suppress it
829*67e74705SXin Li     // during their IR-generation.
830*67e74705SXin Li     if (getLangOpts().ObjCAutoRefCount &&
831*67e74705SXin Li         !CurFnInfo->isReturnsRetained() &&
832*67e74705SXin Li         RetTy->isObjCRetainableType())
833*67e74705SXin Li       AutoreleaseResult = true;
834*67e74705SXin Li   }
835*67e74705SXin Li 
836*67e74705SXin Li   EmitStartEHSpec(CurCodeDecl);
837*67e74705SXin Li 
838*67e74705SXin Li   PrologueCleanupDepth = EHStack.stable_begin();
839*67e74705SXin Li   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
840*67e74705SXin Li 
841*67e74705SXin Li   if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
842*67e74705SXin Li     CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
843*67e74705SXin Li     const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
844*67e74705SXin Li     if (MD->getParent()->isLambda() &&
845*67e74705SXin Li         MD->getOverloadedOperator() == OO_Call) {
846*67e74705SXin Li       // We're in a lambda; figure out the captures.
847*67e74705SXin Li       MD->getParent()->getCaptureFields(LambdaCaptureFields,
848*67e74705SXin Li                                         LambdaThisCaptureField);
849*67e74705SXin Li       if (LambdaThisCaptureField) {
850*67e74705SXin Li         // If the lambda captures the object referred to by '*this' - either by
851*67e74705SXin Li         // value or by reference, make sure CXXThisValue points to the correct
852*67e74705SXin Li         // object.
853*67e74705SXin Li 
854*67e74705SXin Li         // Get the lvalue for the field (which is a copy of the enclosing object
855*67e74705SXin Li         // or contains the address of the enclosing object).
856*67e74705SXin Li         LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
857*67e74705SXin Li         if (!LambdaThisCaptureField->getType()->isPointerType()) {
858*67e74705SXin Li           // If the enclosing object was captured by value, just use its address.
859*67e74705SXin Li           CXXThisValue = ThisFieldLValue.getAddress().getPointer();
860*67e74705SXin Li         } else {
861*67e74705SXin Li           // Load the lvalue pointed to by the field, since '*this' was captured
862*67e74705SXin Li           // by reference.
863*67e74705SXin Li           CXXThisValue =
864*67e74705SXin Li               EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
865*67e74705SXin Li         }
866*67e74705SXin Li       }
867*67e74705SXin Li       for (auto *FD : MD->getParent()->fields()) {
868*67e74705SXin Li         if (FD->hasCapturedVLAType()) {
869*67e74705SXin Li           auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
870*67e74705SXin Li                                            SourceLocation()).getScalarVal();
871*67e74705SXin Li           auto VAT = FD->getCapturedVLAType();
872*67e74705SXin Li           VLASizeMap[VAT->getSizeExpr()] = ExprArg;
873*67e74705SXin Li         }
874*67e74705SXin Li       }
875*67e74705SXin Li     } else {
876*67e74705SXin Li       // Not in a lambda; just use 'this' from the method.
877*67e74705SXin Li       // FIXME: Should we generate a new load for each use of 'this'?  The
878*67e74705SXin Li       // fast register allocator would be happier...
879*67e74705SXin Li       CXXThisValue = CXXABIThisValue;
880*67e74705SXin Li     }
881*67e74705SXin Li   }
882*67e74705SXin Li 
883*67e74705SXin Li   // If any of the arguments have a variably modified type, make sure to
884*67e74705SXin Li   // emit the type size.
885*67e74705SXin Li   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
886*67e74705SXin Li        i != e; ++i) {
887*67e74705SXin Li     const VarDecl *VD = *i;
888*67e74705SXin Li 
889*67e74705SXin Li     // Dig out the type as written from ParmVarDecls; it's unclear whether
890*67e74705SXin Li     // the standard (C99 6.9.1p10) requires this, but we're following the
891*67e74705SXin Li     // precedent set by gcc.
892*67e74705SXin Li     QualType Ty;
893*67e74705SXin Li     if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
894*67e74705SXin Li       Ty = PVD->getOriginalType();
895*67e74705SXin Li     else
896*67e74705SXin Li       Ty = VD->getType();
897*67e74705SXin Li 
898*67e74705SXin Li     if (Ty->isVariablyModifiedType())
899*67e74705SXin Li       EmitVariablyModifiedType(Ty);
900*67e74705SXin Li   }
901*67e74705SXin Li   // Emit a location at the end of the prologue.
902*67e74705SXin Li   if (CGDebugInfo *DI = getDebugInfo())
903*67e74705SXin Li     DI->EmitLocation(Builder, StartLoc);
904*67e74705SXin Li }
905*67e74705SXin Li 
EmitFunctionBody(FunctionArgList & Args,const Stmt * Body)906*67e74705SXin Li void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args,
907*67e74705SXin Li                                        const Stmt *Body) {
908*67e74705SXin Li   incrementProfileCounter(Body);
909*67e74705SXin Li   if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
910*67e74705SXin Li     EmitCompoundStmtWithoutScope(*S);
911*67e74705SXin Li   else
912*67e74705SXin Li     EmitStmt(Body);
913*67e74705SXin Li }
914*67e74705SXin Li 
915*67e74705SXin Li /// When instrumenting to collect profile data, the counts for some blocks
916*67e74705SXin Li /// such as switch cases need to not include the fall-through counts, so
917*67e74705SXin Li /// emit a branch around the instrumentation code. When not instrumenting,
918*67e74705SXin Li /// this just calls EmitBlock().
EmitBlockWithFallThrough(llvm::BasicBlock * BB,const Stmt * S)919*67e74705SXin Li void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
920*67e74705SXin Li                                                const Stmt *S) {
921*67e74705SXin Li   llvm::BasicBlock *SkipCountBB = nullptr;
922*67e74705SXin Li   if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) {
923*67e74705SXin Li     // When instrumenting for profiling, the fallthrough to certain
924*67e74705SXin Li     // statements needs to skip over the instrumentation code so that we
925*67e74705SXin Li     // get an accurate count.
926*67e74705SXin Li     SkipCountBB = createBasicBlock("skipcount");
927*67e74705SXin Li     EmitBranch(SkipCountBB);
928*67e74705SXin Li   }
929*67e74705SXin Li   EmitBlock(BB);
930*67e74705SXin Li   uint64_t CurrentCount = getCurrentProfileCount();
931*67e74705SXin Li   incrementProfileCounter(S);
932*67e74705SXin Li   setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
933*67e74705SXin Li   if (SkipCountBB)
934*67e74705SXin Li     EmitBlock(SkipCountBB);
935*67e74705SXin Li }
936*67e74705SXin Li 
937*67e74705SXin Li /// Tries to mark the given function nounwind based on the
938*67e74705SXin Li /// non-existence of any throwing calls within it.  We believe this is
939*67e74705SXin Li /// lightweight enough to do at -O0.
TryMarkNoThrow(llvm::Function * F)940*67e74705SXin Li static void TryMarkNoThrow(llvm::Function *F) {
941*67e74705SXin Li   // LLVM treats 'nounwind' on a function as part of the type, so we
942*67e74705SXin Li   // can't do this on functions that can be overwritten.
943*67e74705SXin Li   if (F->isInterposable()) return;
944*67e74705SXin Li 
945*67e74705SXin Li   for (llvm::BasicBlock &BB : *F)
946*67e74705SXin Li     for (llvm::Instruction &I : BB)
947*67e74705SXin Li       if (I.mayThrow())
948*67e74705SXin Li         return;
949*67e74705SXin Li 
950*67e74705SXin Li   F->setDoesNotThrow();
951*67e74705SXin Li }
952*67e74705SXin Li 
BuildFunctionArgList(GlobalDecl GD,FunctionArgList & Args)953*67e74705SXin Li QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
954*67e74705SXin Li                                                FunctionArgList &Args) {
955*67e74705SXin Li   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
956*67e74705SXin Li   QualType ResTy = FD->getReturnType();
957*67e74705SXin Li 
958*67e74705SXin Li   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
959*67e74705SXin Li   if (MD && MD->isInstance()) {
960*67e74705SXin Li     if (CGM.getCXXABI().HasThisReturn(GD))
961*67e74705SXin Li       ResTy = MD->getThisType(getContext());
962*67e74705SXin Li     else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
963*67e74705SXin Li       ResTy = CGM.getContext().VoidPtrTy;
964*67e74705SXin Li     CGM.getCXXABI().buildThisParam(*this, Args);
965*67e74705SXin Li   }
966*67e74705SXin Li 
967*67e74705SXin Li   // The base version of an inheriting constructor whose constructed base is a
968*67e74705SXin Li   // virtual base is not passed any arguments (because it doesn't actually call
969*67e74705SXin Li   // the inherited constructor).
970*67e74705SXin Li   bool PassedParams = true;
971*67e74705SXin Li   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
972*67e74705SXin Li     if (auto Inherited = CD->getInheritedConstructor())
973*67e74705SXin Li       PassedParams =
974*67e74705SXin Li           getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
975*67e74705SXin Li 
976*67e74705SXin Li   if (PassedParams) {
977*67e74705SXin Li     for (auto *Param : FD->parameters()) {
978*67e74705SXin Li       Args.push_back(Param);
979*67e74705SXin Li       if (!Param->hasAttr<PassObjectSizeAttr>())
980*67e74705SXin Li         continue;
981*67e74705SXin Li 
982*67e74705SXin Li       IdentifierInfo *NoID = nullptr;
983*67e74705SXin Li       auto *Implicit = ImplicitParamDecl::Create(
984*67e74705SXin Li           getContext(), Param->getDeclContext(), Param->getLocation(), NoID,
985*67e74705SXin Li           getContext().getSizeType());
986*67e74705SXin Li       SizeArguments[Param] = Implicit;
987*67e74705SXin Li       Args.push_back(Implicit);
988*67e74705SXin Li     }
989*67e74705SXin Li   }
990*67e74705SXin Li 
991*67e74705SXin Li   if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
992*67e74705SXin Li     CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
993*67e74705SXin Li 
994*67e74705SXin Li   return ResTy;
995*67e74705SXin Li }
996*67e74705SXin Li 
GenerateCode(GlobalDecl GD,llvm::Function * Fn,const CGFunctionInfo & FnInfo)997*67e74705SXin Li void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
998*67e74705SXin Li                                    const CGFunctionInfo &FnInfo) {
999*67e74705SXin Li   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1000*67e74705SXin Li   CurGD = GD;
1001*67e74705SXin Li 
1002*67e74705SXin Li   FunctionArgList Args;
1003*67e74705SXin Li   QualType ResTy = BuildFunctionArgList(GD, Args);
1004*67e74705SXin Li 
1005*67e74705SXin Li   // Check if we should generate debug info for this function.
1006*67e74705SXin Li   if (FD->hasAttr<NoDebugAttr>())
1007*67e74705SXin Li     DebugInfo = nullptr; // disable debug info indefinitely for this function
1008*67e74705SXin Li 
1009*67e74705SXin Li   SourceRange BodyRange;
1010*67e74705SXin Li   if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
1011*67e74705SXin Li   CurEHLocation = BodyRange.getEnd();
1012*67e74705SXin Li 
1013*67e74705SXin Li   // Use the location of the start of the function to determine where
1014*67e74705SXin Li   // the function definition is located. By default use the location
1015*67e74705SXin Li   // of the declaration as the location for the subprogram. A function
1016*67e74705SXin Li   // may lack a declaration in the source code if it is created by code
1017*67e74705SXin Li   // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
1018*67e74705SXin Li   SourceLocation Loc = FD->getLocation();
1019*67e74705SXin Li 
1020*67e74705SXin Li   // If this is a function specialization then use the pattern body
1021*67e74705SXin Li   // as the location for the function.
1022*67e74705SXin Li   if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
1023*67e74705SXin Li     if (SpecDecl->hasBody(SpecDecl))
1024*67e74705SXin Li       Loc = SpecDecl->getLocation();
1025*67e74705SXin Li 
1026*67e74705SXin Li   // Emit the standard function prologue.
1027*67e74705SXin Li   StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
1028*67e74705SXin Li 
1029*67e74705SXin Li   // Generate the body of the function.
1030*67e74705SXin Li   PGO.assignRegionCounters(GD, CurFn);
1031*67e74705SXin Li   if (isa<CXXDestructorDecl>(FD))
1032*67e74705SXin Li     EmitDestructorBody(Args);
1033*67e74705SXin Li   else if (isa<CXXConstructorDecl>(FD))
1034*67e74705SXin Li     EmitConstructorBody(Args);
1035*67e74705SXin Li   else if (getLangOpts().CUDA &&
1036*67e74705SXin Li            !getLangOpts().CUDAIsDevice &&
1037*67e74705SXin Li            FD->hasAttr<CUDAGlobalAttr>())
1038*67e74705SXin Li     CGM.getCUDARuntime().emitDeviceStub(*this, Args);
1039*67e74705SXin Li   else if (isa<CXXConversionDecl>(FD) &&
1040*67e74705SXin Li            cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) {
1041*67e74705SXin Li     // The lambda conversion to block pointer is special; the semantics can't be
1042*67e74705SXin Li     // expressed in the AST, so IRGen needs to special-case it.
1043*67e74705SXin Li     EmitLambdaToBlockPointerBody(Args);
1044*67e74705SXin Li   } else if (isa<CXXMethodDecl>(FD) &&
1045*67e74705SXin Li              cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
1046*67e74705SXin Li     // The lambda static invoker function is special, because it forwards or
1047*67e74705SXin Li     // clones the body of the function call operator (but is actually static).
1048*67e74705SXin Li     EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD));
1049*67e74705SXin Li   } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
1050*67e74705SXin Li              (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
1051*67e74705SXin Li               cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
1052*67e74705SXin Li     // Implicit copy-assignment gets the same special treatment as implicit
1053*67e74705SXin Li     // copy-constructors.
1054*67e74705SXin Li     emitImplicitAssignmentOperatorBody(Args);
1055*67e74705SXin Li   } else if (Stmt *Body = FD->getBody()) {
1056*67e74705SXin Li     EmitFunctionBody(Args, Body);
1057*67e74705SXin Li   } else
1058*67e74705SXin Li     llvm_unreachable("no definition for emitted function");
1059*67e74705SXin Li 
1060*67e74705SXin Li   // C++11 [stmt.return]p2:
1061*67e74705SXin Li   //   Flowing off the end of a function [...] results in undefined behavior in
1062*67e74705SXin Li   //   a value-returning function.
1063*67e74705SXin Li   // C11 6.9.1p12:
1064*67e74705SXin Li   //   If the '}' that terminates a function is reached, and the value of the
1065*67e74705SXin Li   //   function call is used by the caller, the behavior is undefined.
1066*67e74705SXin Li   if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
1067*67e74705SXin Li       !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
1068*67e74705SXin Li     if (SanOpts.has(SanitizerKind::Return)) {
1069*67e74705SXin Li       SanitizerScope SanScope(this);
1070*67e74705SXin Li       llvm::Value *IsFalse = Builder.getFalse();
1071*67e74705SXin Li       EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
1072*67e74705SXin Li                 "missing_return", EmitCheckSourceLocation(FD->getLocation()),
1073*67e74705SXin Li                 None);
1074*67e74705SXin Li     } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1075*67e74705SXin Li       EmitTrapCall(llvm::Intrinsic::trap);
1076*67e74705SXin Li     }
1077*67e74705SXin Li     Builder.CreateUnreachable();
1078*67e74705SXin Li     Builder.ClearInsertionPoint();
1079*67e74705SXin Li   }
1080*67e74705SXin Li 
1081*67e74705SXin Li   // Emit the standard function epilogue.
1082*67e74705SXin Li   FinishFunction(BodyRange.getEnd());
1083*67e74705SXin Li 
1084*67e74705SXin Li   // If we haven't marked the function nothrow through other means, do
1085*67e74705SXin Li   // a quick pass now to see if we can.
1086*67e74705SXin Li   if (!CurFn->doesNotThrow())
1087*67e74705SXin Li     TryMarkNoThrow(CurFn);
1088*67e74705SXin Li }
1089*67e74705SXin Li 
1090*67e74705SXin Li /// ContainsLabel - Return true if the statement contains a label in it.  If
1091*67e74705SXin Li /// this statement is not executed normally, it not containing a label means
1092*67e74705SXin Li /// that we can just remove the code.
ContainsLabel(const Stmt * S,bool IgnoreCaseStmts)1093*67e74705SXin Li bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
1094*67e74705SXin Li   // Null statement, not a label!
1095*67e74705SXin Li   if (!S) return false;
1096*67e74705SXin Li 
1097*67e74705SXin Li   // If this is a label, we have to emit the code, consider something like:
1098*67e74705SXin Li   // if (0) {  ...  foo:  bar(); }  goto foo;
1099*67e74705SXin Li   //
1100*67e74705SXin Li   // TODO: If anyone cared, we could track __label__'s, since we know that you
1101*67e74705SXin Li   // can't jump to one from outside their declared region.
1102*67e74705SXin Li   if (isa<LabelStmt>(S))
1103*67e74705SXin Li     return true;
1104*67e74705SXin Li 
1105*67e74705SXin Li   // If this is a case/default statement, and we haven't seen a switch, we have
1106*67e74705SXin Li   // to emit the code.
1107*67e74705SXin Li   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
1108*67e74705SXin Li     return true;
1109*67e74705SXin Li 
1110*67e74705SXin Li   // If this is a switch statement, we want to ignore cases below it.
1111*67e74705SXin Li   if (isa<SwitchStmt>(S))
1112*67e74705SXin Li     IgnoreCaseStmts = true;
1113*67e74705SXin Li 
1114*67e74705SXin Li   // Scan subexpressions for verboten labels.
1115*67e74705SXin Li   for (const Stmt *SubStmt : S->children())
1116*67e74705SXin Li     if (ContainsLabel(SubStmt, IgnoreCaseStmts))
1117*67e74705SXin Li       return true;
1118*67e74705SXin Li 
1119*67e74705SXin Li   return false;
1120*67e74705SXin Li }
1121*67e74705SXin Li 
1122*67e74705SXin Li /// containsBreak - Return true if the statement contains a break out of it.
1123*67e74705SXin Li /// If the statement (recursively) contains a switch or loop with a break
1124*67e74705SXin Li /// inside of it, this is fine.
containsBreak(const Stmt * S)1125*67e74705SXin Li bool CodeGenFunction::containsBreak(const Stmt *S) {
1126*67e74705SXin Li   // Null statement, not a label!
1127*67e74705SXin Li   if (!S) return false;
1128*67e74705SXin Li 
1129*67e74705SXin Li   // If this is a switch or loop that defines its own break scope, then we can
1130*67e74705SXin Li   // include it and anything inside of it.
1131*67e74705SXin Li   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
1132*67e74705SXin Li       isa<ForStmt>(S))
1133*67e74705SXin Li     return false;
1134*67e74705SXin Li 
1135*67e74705SXin Li   if (isa<BreakStmt>(S))
1136*67e74705SXin Li     return true;
1137*67e74705SXin Li 
1138*67e74705SXin Li   // Scan subexpressions for verboten breaks.
1139*67e74705SXin Li   for (const Stmt *SubStmt : S->children())
1140*67e74705SXin Li     if (containsBreak(SubStmt))
1141*67e74705SXin Li       return true;
1142*67e74705SXin Li 
1143*67e74705SXin Li   return false;
1144*67e74705SXin Li }
1145*67e74705SXin Li 
1146*67e74705SXin Li 
1147*67e74705SXin Li /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1148*67e74705SXin Li /// to a constant, or if it does but contains a label, return false.  If it
1149*67e74705SXin Li /// constant folds return true and set the boolean result in Result.
ConstantFoldsToSimpleInteger(const Expr * Cond,bool & ResultBool,bool AllowLabels)1150*67e74705SXin Li bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1151*67e74705SXin Li                                                    bool &ResultBool,
1152*67e74705SXin Li                                                    bool AllowLabels) {
1153*67e74705SXin Li   llvm::APSInt ResultInt;
1154*67e74705SXin Li   if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
1155*67e74705SXin Li     return false;
1156*67e74705SXin Li 
1157*67e74705SXin Li   ResultBool = ResultInt.getBoolValue();
1158*67e74705SXin Li   return true;
1159*67e74705SXin Li }
1160*67e74705SXin Li 
1161*67e74705SXin Li /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1162*67e74705SXin Li /// to a constant, or if it does but contains a label, return false.  If it
1163*67e74705SXin Li /// constant folds return true and set the folded value.
ConstantFoldsToSimpleInteger(const Expr * Cond,llvm::APSInt & ResultInt,bool AllowLabels)1164*67e74705SXin Li bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1165*67e74705SXin Li                                                    llvm::APSInt &ResultInt,
1166*67e74705SXin Li                                                    bool AllowLabels) {
1167*67e74705SXin Li   // FIXME: Rename and handle conversion of other evaluatable things
1168*67e74705SXin Li   // to bool.
1169*67e74705SXin Li   llvm::APSInt Int;
1170*67e74705SXin Li   if (!Cond->EvaluateAsInt(Int, getContext()))
1171*67e74705SXin Li     return false;  // Not foldable, not integer or not fully evaluatable.
1172*67e74705SXin Li 
1173*67e74705SXin Li   if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
1174*67e74705SXin Li     return false;  // Contains a label.
1175*67e74705SXin Li 
1176*67e74705SXin Li   ResultInt = Int;
1177*67e74705SXin Li   return true;
1178*67e74705SXin Li }
1179*67e74705SXin Li 
1180*67e74705SXin Li 
1181*67e74705SXin Li 
1182*67e74705SXin Li /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1183*67e74705SXin Li /// statement) to the specified blocks.  Based on the condition, this might try
1184*67e74705SXin Li /// to simplify the codegen of the conditional based on the branch.
1185*67e74705SXin Li ///
EmitBranchOnBoolExpr(const Expr * Cond,llvm::BasicBlock * TrueBlock,llvm::BasicBlock * FalseBlock,uint64_t TrueCount)1186*67e74705SXin Li void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
1187*67e74705SXin Li                                            llvm::BasicBlock *TrueBlock,
1188*67e74705SXin Li                                            llvm::BasicBlock *FalseBlock,
1189*67e74705SXin Li                                            uint64_t TrueCount) {
1190*67e74705SXin Li   Cond = Cond->IgnoreParens();
1191*67e74705SXin Li 
1192*67e74705SXin Li   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
1193*67e74705SXin Li 
1194*67e74705SXin Li     // Handle X && Y in a condition.
1195*67e74705SXin Li     if (CondBOp->getOpcode() == BO_LAnd) {
1196*67e74705SXin Li       // If we have "1 && X", simplify the code.  "0 && X" would have constant
1197*67e74705SXin Li       // folded if the case was simple enough.
1198*67e74705SXin Li       bool ConstantBool = false;
1199*67e74705SXin Li       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1200*67e74705SXin Li           ConstantBool) {
1201*67e74705SXin Li         // br(1 && X) -> br(X).
1202*67e74705SXin Li         incrementProfileCounter(CondBOp);
1203*67e74705SXin Li         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
1204*67e74705SXin Li                                     TrueCount);
1205*67e74705SXin Li       }
1206*67e74705SXin Li 
1207*67e74705SXin Li       // If we have "X && 1", simplify the code to use an uncond branch.
1208*67e74705SXin Li       // "X && 0" would have been constant folded to 0.
1209*67e74705SXin Li       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1210*67e74705SXin Li           ConstantBool) {
1211*67e74705SXin Li         // br(X && 1) -> br(X).
1212*67e74705SXin Li         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
1213*67e74705SXin Li                                     TrueCount);
1214*67e74705SXin Li       }
1215*67e74705SXin Li 
1216*67e74705SXin Li       // Emit the LHS as a conditional.  If the LHS conditional is false, we
1217*67e74705SXin Li       // want to jump to the FalseBlock.
1218*67e74705SXin Li       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
1219*67e74705SXin Li       // The counter tells us how often we evaluate RHS, and all of TrueCount
1220*67e74705SXin Li       // can be propagated to that branch.
1221*67e74705SXin Li       uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
1222*67e74705SXin Li 
1223*67e74705SXin Li       ConditionalEvaluation eval(*this);
1224*67e74705SXin Li       {
1225*67e74705SXin Li         ApplyDebugLocation DL(*this, Cond);
1226*67e74705SXin Li         EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
1227*67e74705SXin Li         EmitBlock(LHSTrue);
1228*67e74705SXin Li       }
1229*67e74705SXin Li 
1230*67e74705SXin Li       incrementProfileCounter(CondBOp);
1231*67e74705SXin Li       setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1232*67e74705SXin Li 
1233*67e74705SXin Li       // Any temporaries created here are conditional.
1234*67e74705SXin Li       eval.begin(*this);
1235*67e74705SXin Li       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount);
1236*67e74705SXin Li       eval.end(*this);
1237*67e74705SXin Li 
1238*67e74705SXin Li       return;
1239*67e74705SXin Li     }
1240*67e74705SXin Li 
1241*67e74705SXin Li     if (CondBOp->getOpcode() == BO_LOr) {
1242*67e74705SXin Li       // If we have "0 || X", simplify the code.  "1 || X" would have constant
1243*67e74705SXin Li       // folded if the case was simple enough.
1244*67e74705SXin Li       bool ConstantBool = false;
1245*67e74705SXin Li       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1246*67e74705SXin Li           !ConstantBool) {
1247*67e74705SXin Li         // br(0 || X) -> br(X).
1248*67e74705SXin Li         incrementProfileCounter(CondBOp);
1249*67e74705SXin Li         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
1250*67e74705SXin Li                                     TrueCount);
1251*67e74705SXin Li       }
1252*67e74705SXin Li 
1253*67e74705SXin Li       // If we have "X || 0", simplify the code to use an uncond branch.
1254*67e74705SXin Li       // "X || 1" would have been constant folded to 1.
1255*67e74705SXin Li       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1256*67e74705SXin Li           !ConstantBool) {
1257*67e74705SXin Li         // br(X || 0) -> br(X).
1258*67e74705SXin Li         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
1259*67e74705SXin Li                                     TrueCount);
1260*67e74705SXin Li       }
1261*67e74705SXin Li 
1262*67e74705SXin Li       // Emit the LHS as a conditional.  If the LHS conditional is true, we
1263*67e74705SXin Li       // want to jump to the TrueBlock.
1264*67e74705SXin Li       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
1265*67e74705SXin Li       // We have the count for entry to the RHS and for the whole expression
1266*67e74705SXin Li       // being true, so we can divy up True count between the short circuit and
1267*67e74705SXin Li       // the RHS.
1268*67e74705SXin Li       uint64_t LHSCount =
1269*67e74705SXin Li           getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
1270*67e74705SXin Li       uint64_t RHSCount = TrueCount - LHSCount;
1271*67e74705SXin Li 
1272*67e74705SXin Li       ConditionalEvaluation eval(*this);
1273*67e74705SXin Li       {
1274*67e74705SXin Li         ApplyDebugLocation DL(*this, Cond);
1275*67e74705SXin Li         EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
1276*67e74705SXin Li         EmitBlock(LHSFalse);
1277*67e74705SXin Li       }
1278*67e74705SXin Li 
1279*67e74705SXin Li       incrementProfileCounter(CondBOp);
1280*67e74705SXin Li       setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1281*67e74705SXin Li 
1282*67e74705SXin Li       // Any temporaries created here are conditional.
1283*67e74705SXin Li       eval.begin(*this);
1284*67e74705SXin Li       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount);
1285*67e74705SXin Li 
1286*67e74705SXin Li       eval.end(*this);
1287*67e74705SXin Li 
1288*67e74705SXin Li       return;
1289*67e74705SXin Li     }
1290*67e74705SXin Li   }
1291*67e74705SXin Li 
1292*67e74705SXin Li   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1293*67e74705SXin Li     // br(!x, t, f) -> br(x, f, t)
1294*67e74705SXin Li     if (CondUOp->getOpcode() == UO_LNot) {
1295*67e74705SXin Li       // Negate the count.
1296*67e74705SXin Li       uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
1297*67e74705SXin Li       // Negate the condition and swap the destination blocks.
1298*67e74705SXin Li       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
1299*67e74705SXin Li                                   FalseCount);
1300*67e74705SXin Li     }
1301*67e74705SXin Li   }
1302*67e74705SXin Li 
1303*67e74705SXin Li   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
1304*67e74705SXin Li     // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
1305*67e74705SXin Li     llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
1306*67e74705SXin Li     llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
1307*67e74705SXin Li 
1308*67e74705SXin Li     ConditionalEvaluation cond(*this);
1309*67e74705SXin Li     EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
1310*67e74705SXin Li                          getProfileCount(CondOp));
1311*67e74705SXin Li 
1312*67e74705SXin Li     // When computing PGO branch weights, we only know the overall count for
1313*67e74705SXin Li     // the true block. This code is essentially doing tail duplication of the
1314*67e74705SXin Li     // naive code-gen, introducing new edges for which counts are not
1315*67e74705SXin Li     // available. Divide the counts proportionally between the LHS and RHS of
1316*67e74705SXin Li     // the conditional operator.
1317*67e74705SXin Li     uint64_t LHSScaledTrueCount = 0;
1318*67e74705SXin Li     if (TrueCount) {
1319*67e74705SXin Li       double LHSRatio =
1320*67e74705SXin Li           getProfileCount(CondOp) / (double)getCurrentProfileCount();
1321*67e74705SXin Li       LHSScaledTrueCount = TrueCount * LHSRatio;
1322*67e74705SXin Li     }
1323*67e74705SXin Li 
1324*67e74705SXin Li     cond.begin(*this);
1325*67e74705SXin Li     EmitBlock(LHSBlock);
1326*67e74705SXin Li     incrementProfileCounter(CondOp);
1327*67e74705SXin Li     {
1328*67e74705SXin Li       ApplyDebugLocation DL(*this, Cond);
1329*67e74705SXin Li       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
1330*67e74705SXin Li                            LHSScaledTrueCount);
1331*67e74705SXin Li     }
1332*67e74705SXin Li     cond.end(*this);
1333*67e74705SXin Li 
1334*67e74705SXin Li     cond.begin(*this);
1335*67e74705SXin Li     EmitBlock(RHSBlock);
1336*67e74705SXin Li     EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
1337*67e74705SXin Li                          TrueCount - LHSScaledTrueCount);
1338*67e74705SXin Li     cond.end(*this);
1339*67e74705SXin Li 
1340*67e74705SXin Li     return;
1341*67e74705SXin Li   }
1342*67e74705SXin Li 
1343*67e74705SXin Li   if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
1344*67e74705SXin Li     // Conditional operator handling can give us a throw expression as a
1345*67e74705SXin Li     // condition for a case like:
1346*67e74705SXin Li     //   br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
1347*67e74705SXin Li     // Fold this to:
1348*67e74705SXin Li     //   br(c, throw x, br(y, t, f))
1349*67e74705SXin Li     EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
1350*67e74705SXin Li     return;
1351*67e74705SXin Li   }
1352*67e74705SXin Li 
1353*67e74705SXin Li   // If the branch has a condition wrapped by __builtin_unpredictable,
1354*67e74705SXin Li   // create metadata that specifies that the branch is unpredictable.
1355*67e74705SXin Li   // Don't bother if not optimizing because that metadata would not be used.
1356*67e74705SXin Li   llvm::MDNode *Unpredictable = nullptr;
1357*67e74705SXin Li   auto *Call = dyn_cast<CallExpr>(Cond);
1358*67e74705SXin Li   if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
1359*67e74705SXin Li     auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
1360*67e74705SXin Li     if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
1361*67e74705SXin Li       llvm::MDBuilder MDHelper(getLLVMContext());
1362*67e74705SXin Li       Unpredictable = MDHelper.createUnpredictable();
1363*67e74705SXin Li     }
1364*67e74705SXin Li   }
1365*67e74705SXin Li 
1366*67e74705SXin Li   // Create branch weights based on the number of times we get here and the
1367*67e74705SXin Li   // number of times the condition should be true.
1368*67e74705SXin Li   uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
1369*67e74705SXin Li   llvm::MDNode *Weights =
1370*67e74705SXin Li       createProfileWeights(TrueCount, CurrentCount - TrueCount);
1371*67e74705SXin Li 
1372*67e74705SXin Li   // Emit the code with the fully general case.
1373*67e74705SXin Li   llvm::Value *CondV;
1374*67e74705SXin Li   {
1375*67e74705SXin Li     ApplyDebugLocation DL(*this, Cond);
1376*67e74705SXin Li     CondV = EvaluateExprAsBool(Cond);
1377*67e74705SXin Li   }
1378*67e74705SXin Li   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
1379*67e74705SXin Li }
1380*67e74705SXin Li 
1381*67e74705SXin Li /// ErrorUnsupported - Print out an error that codegen doesn't support the
1382*67e74705SXin Li /// specified stmt yet.
ErrorUnsupported(const Stmt * S,const char * Type)1383*67e74705SXin Li void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
1384*67e74705SXin Li   CGM.ErrorUnsupported(S, Type);
1385*67e74705SXin Li }
1386*67e74705SXin Li 
1387*67e74705SXin Li /// emitNonZeroVLAInit - Emit the "zero" initialization of a
1388*67e74705SXin Li /// variable-length array whose elements have a non-zero bit-pattern.
1389*67e74705SXin Li ///
1390*67e74705SXin Li /// \param baseType the inner-most element type of the array
1391*67e74705SXin Li /// \param src - a char* pointing to the bit-pattern for a single
1392*67e74705SXin Li /// base element of the array
1393*67e74705SXin Li /// \param sizeInChars - the total size of the VLA, in chars
emitNonZeroVLAInit(CodeGenFunction & CGF,QualType baseType,Address dest,Address src,llvm::Value * sizeInChars)1394*67e74705SXin Li static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
1395*67e74705SXin Li                                Address dest, Address src,
1396*67e74705SXin Li                                llvm::Value *sizeInChars) {
1397*67e74705SXin Li   CGBuilderTy &Builder = CGF.Builder;
1398*67e74705SXin Li 
1399*67e74705SXin Li   CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
1400*67e74705SXin Li   llvm::Value *baseSizeInChars
1401*67e74705SXin Li     = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
1402*67e74705SXin Li 
1403*67e74705SXin Li   Address begin =
1404*67e74705SXin Li     Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin");
1405*67e74705SXin Li   llvm::Value *end =
1406*67e74705SXin Li     Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars, "vla.end");
1407*67e74705SXin Li 
1408*67e74705SXin Li   llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
1409*67e74705SXin Li   llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
1410*67e74705SXin Li   llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
1411*67e74705SXin Li 
1412*67e74705SXin Li   // Make a loop over the VLA.  C99 guarantees that the VLA element
1413*67e74705SXin Li   // count must be nonzero.
1414*67e74705SXin Li   CGF.EmitBlock(loopBB);
1415*67e74705SXin Li 
1416*67e74705SXin Li   llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
1417*67e74705SXin Li   cur->addIncoming(begin.getPointer(), originBB);
1418*67e74705SXin Li 
1419*67e74705SXin Li   CharUnits curAlign =
1420*67e74705SXin Li     dest.getAlignment().alignmentOfArrayElement(baseSize);
1421*67e74705SXin Li 
1422*67e74705SXin Li   // memcpy the individual element bit-pattern.
1423*67e74705SXin Li   Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars,
1424*67e74705SXin Li                        /*volatile*/ false);
1425*67e74705SXin Li 
1426*67e74705SXin Li   // Go to the next element.
1427*67e74705SXin Li   llvm::Value *next =
1428*67e74705SXin Li     Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
1429*67e74705SXin Li 
1430*67e74705SXin Li   // Leave if that's the end of the VLA.
1431*67e74705SXin Li   llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
1432*67e74705SXin Li   Builder.CreateCondBr(done, contBB, loopBB);
1433*67e74705SXin Li   cur->addIncoming(next, loopBB);
1434*67e74705SXin Li 
1435*67e74705SXin Li   CGF.EmitBlock(contBB);
1436*67e74705SXin Li }
1437*67e74705SXin Li 
1438*67e74705SXin Li void
EmitNullInitialization(Address DestPtr,QualType Ty)1439*67e74705SXin Li CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
1440*67e74705SXin Li   // Ignore empty classes in C++.
1441*67e74705SXin Li   if (getLangOpts().CPlusPlus) {
1442*67e74705SXin Li     if (const RecordType *RT = Ty->getAs<RecordType>()) {
1443*67e74705SXin Li       if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
1444*67e74705SXin Li         return;
1445*67e74705SXin Li     }
1446*67e74705SXin Li   }
1447*67e74705SXin Li 
1448*67e74705SXin Li   // Cast the dest ptr to the appropriate i8 pointer type.
1449*67e74705SXin Li   if (DestPtr.getElementType() != Int8Ty)
1450*67e74705SXin Li     DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
1451*67e74705SXin Li 
1452*67e74705SXin Li   // Get size and alignment info for this aggregate.
1453*67e74705SXin Li   CharUnits size = getContext().getTypeSizeInChars(Ty);
1454*67e74705SXin Li 
1455*67e74705SXin Li   llvm::Value *SizeVal;
1456*67e74705SXin Li   const VariableArrayType *vla;
1457*67e74705SXin Li 
1458*67e74705SXin Li   // Don't bother emitting a zero-byte memset.
1459*67e74705SXin Li   if (size.isZero()) {
1460*67e74705SXin Li     // But note that getTypeInfo returns 0 for a VLA.
1461*67e74705SXin Li     if (const VariableArrayType *vlaType =
1462*67e74705SXin Li           dyn_cast_or_null<VariableArrayType>(
1463*67e74705SXin Li                                           getContext().getAsArrayType(Ty))) {
1464*67e74705SXin Li       QualType eltType;
1465*67e74705SXin Li       llvm::Value *numElts;
1466*67e74705SXin Li       std::tie(numElts, eltType) = getVLASize(vlaType);
1467*67e74705SXin Li 
1468*67e74705SXin Li       SizeVal = numElts;
1469*67e74705SXin Li       CharUnits eltSize = getContext().getTypeSizeInChars(eltType);
1470*67e74705SXin Li       if (!eltSize.isOne())
1471*67e74705SXin Li         SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
1472*67e74705SXin Li       vla = vlaType;
1473*67e74705SXin Li     } else {
1474*67e74705SXin Li       return;
1475*67e74705SXin Li     }
1476*67e74705SXin Li   } else {
1477*67e74705SXin Li     SizeVal = CGM.getSize(size);
1478*67e74705SXin Li     vla = nullptr;
1479*67e74705SXin Li   }
1480*67e74705SXin Li 
1481*67e74705SXin Li   // If the type contains a pointer to data member we can't memset it to zero.
1482*67e74705SXin Li   // Instead, create a null constant and copy it to the destination.
1483*67e74705SXin Li   // TODO: there are other patterns besides zero that we can usefully memset,
1484*67e74705SXin Li   // like -1, which happens to be the pattern used by member-pointers.
1485*67e74705SXin Li   if (!CGM.getTypes().isZeroInitializable(Ty)) {
1486*67e74705SXin Li     // For a VLA, emit a single element, then splat that over the VLA.
1487*67e74705SXin Li     if (vla) Ty = getContext().getBaseElementType(vla);
1488*67e74705SXin Li 
1489*67e74705SXin Li     llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
1490*67e74705SXin Li 
1491*67e74705SXin Li     llvm::GlobalVariable *NullVariable =
1492*67e74705SXin Li       new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
1493*67e74705SXin Li                                /*isConstant=*/true,
1494*67e74705SXin Li                                llvm::GlobalVariable::PrivateLinkage,
1495*67e74705SXin Li                                NullConstant, Twine());
1496*67e74705SXin Li     CharUnits NullAlign = DestPtr.getAlignment();
1497*67e74705SXin Li     NullVariable->setAlignment(NullAlign.getQuantity());
1498*67e74705SXin Li     Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()),
1499*67e74705SXin Li                    NullAlign);
1500*67e74705SXin Li 
1501*67e74705SXin Li     if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
1502*67e74705SXin Li 
1503*67e74705SXin Li     // Get and call the appropriate llvm.memcpy overload.
1504*67e74705SXin Li     Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
1505*67e74705SXin Li     return;
1506*67e74705SXin Li   }
1507*67e74705SXin Li 
1508*67e74705SXin Li   // Otherwise, just memset the whole thing to zero.  This is legal
1509*67e74705SXin Li   // because in LLVM, all default initializers (other than the ones we just
1510*67e74705SXin Li   // handled above) are guaranteed to have a bit pattern of all zeros.
1511*67e74705SXin Li   Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
1512*67e74705SXin Li }
1513*67e74705SXin Li 
GetAddrOfLabel(const LabelDecl * L)1514*67e74705SXin Li llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
1515*67e74705SXin Li   // Make sure that there is a block for the indirect goto.
1516*67e74705SXin Li   if (!IndirectBranch)
1517*67e74705SXin Li     GetIndirectGotoBlock();
1518*67e74705SXin Li 
1519*67e74705SXin Li   llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
1520*67e74705SXin Li 
1521*67e74705SXin Li   // Make sure the indirect branch includes all of the address-taken blocks.
1522*67e74705SXin Li   IndirectBranch->addDestination(BB);
1523*67e74705SXin Li   return llvm::BlockAddress::get(CurFn, BB);
1524*67e74705SXin Li }
1525*67e74705SXin Li 
GetIndirectGotoBlock()1526*67e74705SXin Li llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
1527*67e74705SXin Li   // If we already made the indirect branch for indirect goto, return its block.
1528*67e74705SXin Li   if (IndirectBranch) return IndirectBranch->getParent();
1529*67e74705SXin Li 
1530*67e74705SXin Li   CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
1531*67e74705SXin Li 
1532*67e74705SXin Li   // Create the PHI node that indirect gotos will add entries to.
1533*67e74705SXin Li   llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
1534*67e74705SXin Li                                               "indirect.goto.dest");
1535*67e74705SXin Li 
1536*67e74705SXin Li   // Create the indirect branch instruction.
1537*67e74705SXin Li   IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
1538*67e74705SXin Li   return IndirectBranch->getParent();
1539*67e74705SXin Li }
1540*67e74705SXin Li 
1541*67e74705SXin Li /// Computes the length of an array in elements, as well as the base
1542*67e74705SXin Li /// element type and a properly-typed first element pointer.
emitArrayLength(const ArrayType * origArrayType,QualType & baseType,Address & addr)1543*67e74705SXin Li llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
1544*67e74705SXin Li                                               QualType &baseType,
1545*67e74705SXin Li                                               Address &addr) {
1546*67e74705SXin Li   const ArrayType *arrayType = origArrayType;
1547*67e74705SXin Li 
1548*67e74705SXin Li   // If it's a VLA, we have to load the stored size.  Note that
1549*67e74705SXin Li   // this is the size of the VLA in bytes, not its size in elements.
1550*67e74705SXin Li   llvm::Value *numVLAElements = nullptr;
1551*67e74705SXin Li   if (isa<VariableArrayType>(arrayType)) {
1552*67e74705SXin Li     numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first;
1553*67e74705SXin Li 
1554*67e74705SXin Li     // Walk into all VLAs.  This doesn't require changes to addr,
1555*67e74705SXin Li     // which has type T* where T is the first non-VLA element type.
1556*67e74705SXin Li     do {
1557*67e74705SXin Li       QualType elementType = arrayType->getElementType();
1558*67e74705SXin Li       arrayType = getContext().getAsArrayType(elementType);
1559*67e74705SXin Li 
1560*67e74705SXin Li       // If we only have VLA components, 'addr' requires no adjustment.
1561*67e74705SXin Li       if (!arrayType) {
1562*67e74705SXin Li         baseType = elementType;
1563*67e74705SXin Li         return numVLAElements;
1564*67e74705SXin Li       }
1565*67e74705SXin Li     } while (isa<VariableArrayType>(arrayType));
1566*67e74705SXin Li 
1567*67e74705SXin Li     // We get out here only if we find a constant array type
1568*67e74705SXin Li     // inside the VLA.
1569*67e74705SXin Li   }
1570*67e74705SXin Li 
1571*67e74705SXin Li   // We have some number of constant-length arrays, so addr should
1572*67e74705SXin Li   // have LLVM type [M x [N x [...]]]*.  Build a GEP that walks
1573*67e74705SXin Li   // down to the first element of addr.
1574*67e74705SXin Li   SmallVector<llvm::Value*, 8> gepIndices;
1575*67e74705SXin Li 
1576*67e74705SXin Li   // GEP down to the array type.
1577*67e74705SXin Li   llvm::ConstantInt *zero = Builder.getInt32(0);
1578*67e74705SXin Li   gepIndices.push_back(zero);
1579*67e74705SXin Li 
1580*67e74705SXin Li   uint64_t countFromCLAs = 1;
1581*67e74705SXin Li   QualType eltType;
1582*67e74705SXin Li 
1583*67e74705SXin Li   llvm::ArrayType *llvmArrayType =
1584*67e74705SXin Li     dyn_cast<llvm::ArrayType>(addr.getElementType());
1585*67e74705SXin Li   while (llvmArrayType) {
1586*67e74705SXin Li     assert(isa<ConstantArrayType>(arrayType));
1587*67e74705SXin Li     assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
1588*67e74705SXin Li              == llvmArrayType->getNumElements());
1589*67e74705SXin Li 
1590*67e74705SXin Li     gepIndices.push_back(zero);
1591*67e74705SXin Li     countFromCLAs *= llvmArrayType->getNumElements();
1592*67e74705SXin Li     eltType = arrayType->getElementType();
1593*67e74705SXin Li 
1594*67e74705SXin Li     llvmArrayType =
1595*67e74705SXin Li       dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
1596*67e74705SXin Li     arrayType = getContext().getAsArrayType(arrayType->getElementType());
1597*67e74705SXin Li     assert((!llvmArrayType || arrayType) &&
1598*67e74705SXin Li            "LLVM and Clang types are out-of-synch");
1599*67e74705SXin Li   }
1600*67e74705SXin Li 
1601*67e74705SXin Li   if (arrayType) {
1602*67e74705SXin Li     // From this point onwards, the Clang array type has been emitted
1603*67e74705SXin Li     // as some other type (probably a packed struct). Compute the array
1604*67e74705SXin Li     // size, and just emit the 'begin' expression as a bitcast.
1605*67e74705SXin Li     while (arrayType) {
1606*67e74705SXin Li       countFromCLAs *=
1607*67e74705SXin Li           cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
1608*67e74705SXin Li       eltType = arrayType->getElementType();
1609*67e74705SXin Li       arrayType = getContext().getAsArrayType(eltType);
1610*67e74705SXin Li     }
1611*67e74705SXin Li 
1612*67e74705SXin Li     llvm::Type *baseType = ConvertType(eltType);
1613*67e74705SXin Li     addr = Builder.CreateElementBitCast(addr, baseType, "array.begin");
1614*67e74705SXin Li   } else {
1615*67e74705SXin Li     // Create the actual GEP.
1616*67e74705SXin Li     addr = Address(Builder.CreateInBoundsGEP(addr.getPointer(),
1617*67e74705SXin Li                                              gepIndices, "array.begin"),
1618*67e74705SXin Li                    addr.getAlignment());
1619*67e74705SXin Li   }
1620*67e74705SXin Li 
1621*67e74705SXin Li   baseType = eltType;
1622*67e74705SXin Li 
1623*67e74705SXin Li   llvm::Value *numElements
1624*67e74705SXin Li     = llvm::ConstantInt::get(SizeTy, countFromCLAs);
1625*67e74705SXin Li 
1626*67e74705SXin Li   // If we had any VLA dimensions, factor them in.
1627*67e74705SXin Li   if (numVLAElements)
1628*67e74705SXin Li     numElements = Builder.CreateNUWMul(numVLAElements, numElements);
1629*67e74705SXin Li 
1630*67e74705SXin Li   return numElements;
1631*67e74705SXin Li }
1632*67e74705SXin Li 
1633*67e74705SXin Li std::pair<llvm::Value*, QualType>
getVLASize(QualType type)1634*67e74705SXin Li CodeGenFunction::getVLASize(QualType type) {
1635*67e74705SXin Li   const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
1636*67e74705SXin Li   assert(vla && "type was not a variable array type!");
1637*67e74705SXin Li   return getVLASize(vla);
1638*67e74705SXin Li }
1639*67e74705SXin Li 
1640*67e74705SXin Li std::pair<llvm::Value*, QualType>
getVLASize(const VariableArrayType * type)1641*67e74705SXin Li CodeGenFunction::getVLASize(const VariableArrayType *type) {
1642*67e74705SXin Li   // The number of elements so far; always size_t.
1643*67e74705SXin Li   llvm::Value *numElements = nullptr;
1644*67e74705SXin Li 
1645*67e74705SXin Li   QualType elementType;
1646*67e74705SXin Li   do {
1647*67e74705SXin Li     elementType = type->getElementType();
1648*67e74705SXin Li     llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
1649*67e74705SXin Li     assert(vlaSize && "no size for VLA!");
1650*67e74705SXin Li     assert(vlaSize->getType() == SizeTy);
1651*67e74705SXin Li 
1652*67e74705SXin Li     if (!numElements) {
1653*67e74705SXin Li       numElements = vlaSize;
1654*67e74705SXin Li     } else {
1655*67e74705SXin Li       // It's undefined behavior if this wraps around, so mark it that way.
1656*67e74705SXin Li       // FIXME: Teach -fsanitize=undefined to trap this.
1657*67e74705SXin Li       numElements = Builder.CreateNUWMul(numElements, vlaSize);
1658*67e74705SXin Li     }
1659*67e74705SXin Li   } while ((type = getContext().getAsVariableArrayType(elementType)));
1660*67e74705SXin Li 
1661*67e74705SXin Li   return std::pair<llvm::Value*,QualType>(numElements, elementType);
1662*67e74705SXin Li }
1663*67e74705SXin Li 
EmitVariablyModifiedType(QualType type)1664*67e74705SXin Li void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
1665*67e74705SXin Li   assert(type->isVariablyModifiedType() &&
1666*67e74705SXin Li          "Must pass variably modified type to EmitVLASizes!");
1667*67e74705SXin Li 
1668*67e74705SXin Li   EnsureInsertPoint();
1669*67e74705SXin Li 
1670*67e74705SXin Li   // We're going to walk down into the type and look for VLA
1671*67e74705SXin Li   // expressions.
1672*67e74705SXin Li   do {
1673*67e74705SXin Li     assert(type->isVariablyModifiedType());
1674*67e74705SXin Li 
1675*67e74705SXin Li     const Type *ty = type.getTypePtr();
1676*67e74705SXin Li     switch (ty->getTypeClass()) {
1677*67e74705SXin Li 
1678*67e74705SXin Li #define TYPE(Class, Base)
1679*67e74705SXin Li #define ABSTRACT_TYPE(Class, Base)
1680*67e74705SXin Li #define NON_CANONICAL_TYPE(Class, Base)
1681*67e74705SXin Li #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1682*67e74705SXin Li #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
1683*67e74705SXin Li #include "clang/AST/TypeNodes.def"
1684*67e74705SXin Li       llvm_unreachable("unexpected dependent type!");
1685*67e74705SXin Li 
1686*67e74705SXin Li     // These types are never variably-modified.
1687*67e74705SXin Li     case Type::Builtin:
1688*67e74705SXin Li     case Type::Complex:
1689*67e74705SXin Li     case Type::Vector:
1690*67e74705SXin Li     case Type::ExtVector:
1691*67e74705SXin Li     case Type::Record:
1692*67e74705SXin Li     case Type::Enum:
1693*67e74705SXin Li     case Type::Elaborated:
1694*67e74705SXin Li     case Type::TemplateSpecialization:
1695*67e74705SXin Li     case Type::ObjCObject:
1696*67e74705SXin Li     case Type::ObjCInterface:
1697*67e74705SXin Li     case Type::ObjCObjectPointer:
1698*67e74705SXin Li       llvm_unreachable("type class is never variably-modified!");
1699*67e74705SXin Li 
1700*67e74705SXin Li     case Type::Adjusted:
1701*67e74705SXin Li       type = cast<AdjustedType>(ty)->getAdjustedType();
1702*67e74705SXin Li       break;
1703*67e74705SXin Li 
1704*67e74705SXin Li     case Type::Decayed:
1705*67e74705SXin Li       type = cast<DecayedType>(ty)->getPointeeType();
1706*67e74705SXin Li       break;
1707*67e74705SXin Li 
1708*67e74705SXin Li     case Type::Pointer:
1709*67e74705SXin Li       type = cast<PointerType>(ty)->getPointeeType();
1710*67e74705SXin Li       break;
1711*67e74705SXin Li 
1712*67e74705SXin Li     case Type::BlockPointer:
1713*67e74705SXin Li       type = cast<BlockPointerType>(ty)->getPointeeType();
1714*67e74705SXin Li       break;
1715*67e74705SXin Li 
1716*67e74705SXin Li     case Type::LValueReference:
1717*67e74705SXin Li     case Type::RValueReference:
1718*67e74705SXin Li       type = cast<ReferenceType>(ty)->getPointeeType();
1719*67e74705SXin Li       break;
1720*67e74705SXin Li 
1721*67e74705SXin Li     case Type::MemberPointer:
1722*67e74705SXin Li       type = cast<MemberPointerType>(ty)->getPointeeType();
1723*67e74705SXin Li       break;
1724*67e74705SXin Li 
1725*67e74705SXin Li     case Type::ConstantArray:
1726*67e74705SXin Li     case Type::IncompleteArray:
1727*67e74705SXin Li       // Losing element qualification here is fine.
1728*67e74705SXin Li       type = cast<ArrayType>(ty)->getElementType();
1729*67e74705SXin Li       break;
1730*67e74705SXin Li 
1731*67e74705SXin Li     case Type::VariableArray: {
1732*67e74705SXin Li       // Losing element qualification here is fine.
1733*67e74705SXin Li       const VariableArrayType *vat = cast<VariableArrayType>(ty);
1734*67e74705SXin Li 
1735*67e74705SXin Li       // Unknown size indication requires no size computation.
1736*67e74705SXin Li       // Otherwise, evaluate and record it.
1737*67e74705SXin Li       if (const Expr *size = vat->getSizeExpr()) {
1738*67e74705SXin Li         // It's possible that we might have emitted this already,
1739*67e74705SXin Li         // e.g. with a typedef and a pointer to it.
1740*67e74705SXin Li         llvm::Value *&entry = VLASizeMap[size];
1741*67e74705SXin Li         if (!entry) {
1742*67e74705SXin Li           llvm::Value *Size = EmitScalarExpr(size);
1743*67e74705SXin Li 
1744*67e74705SXin Li           // C11 6.7.6.2p5:
1745*67e74705SXin Li           //   If the size is an expression that is not an integer constant
1746*67e74705SXin Li           //   expression [...] each time it is evaluated it shall have a value
1747*67e74705SXin Li           //   greater than zero.
1748*67e74705SXin Li           if (SanOpts.has(SanitizerKind::VLABound) &&
1749*67e74705SXin Li               size->getType()->isSignedIntegerType()) {
1750*67e74705SXin Li             SanitizerScope SanScope(this);
1751*67e74705SXin Li             llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
1752*67e74705SXin Li             llvm::Constant *StaticArgs[] = {
1753*67e74705SXin Li               EmitCheckSourceLocation(size->getLocStart()),
1754*67e74705SXin Li               EmitCheckTypeDescriptor(size->getType())
1755*67e74705SXin Li             };
1756*67e74705SXin Li             EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero),
1757*67e74705SXin Li                                      SanitizerKind::VLABound),
1758*67e74705SXin Li                       "vla_bound_not_positive", StaticArgs, Size);
1759*67e74705SXin Li           }
1760*67e74705SXin Li 
1761*67e74705SXin Li           // Always zexting here would be wrong if it weren't
1762*67e74705SXin Li           // undefined behavior to have a negative bound.
1763*67e74705SXin Li           entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
1764*67e74705SXin Li         }
1765*67e74705SXin Li       }
1766*67e74705SXin Li       type = vat->getElementType();
1767*67e74705SXin Li       break;
1768*67e74705SXin Li     }
1769*67e74705SXin Li 
1770*67e74705SXin Li     case Type::FunctionProto:
1771*67e74705SXin Li     case Type::FunctionNoProto:
1772*67e74705SXin Li       type = cast<FunctionType>(ty)->getReturnType();
1773*67e74705SXin Li       break;
1774*67e74705SXin Li 
1775*67e74705SXin Li     case Type::Paren:
1776*67e74705SXin Li     case Type::TypeOf:
1777*67e74705SXin Li     case Type::UnaryTransform:
1778*67e74705SXin Li     case Type::Attributed:
1779*67e74705SXin Li     case Type::SubstTemplateTypeParm:
1780*67e74705SXin Li     case Type::PackExpansion:
1781*67e74705SXin Li       // Keep walking after single level desugaring.
1782*67e74705SXin Li       type = type.getSingleStepDesugaredType(getContext());
1783*67e74705SXin Li       break;
1784*67e74705SXin Li 
1785*67e74705SXin Li     case Type::Typedef:
1786*67e74705SXin Li     case Type::Decltype:
1787*67e74705SXin Li     case Type::Auto:
1788*67e74705SXin Li       // Stop walking: nothing to do.
1789*67e74705SXin Li       return;
1790*67e74705SXin Li 
1791*67e74705SXin Li     case Type::TypeOfExpr:
1792*67e74705SXin Li       // Stop walking: emit typeof expression.
1793*67e74705SXin Li       EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
1794*67e74705SXin Li       return;
1795*67e74705SXin Li 
1796*67e74705SXin Li     case Type::Atomic:
1797*67e74705SXin Li       type = cast<AtomicType>(ty)->getValueType();
1798*67e74705SXin Li       break;
1799*67e74705SXin Li 
1800*67e74705SXin Li     case Type::Pipe:
1801*67e74705SXin Li       type = cast<PipeType>(ty)->getElementType();
1802*67e74705SXin Li       break;
1803*67e74705SXin Li     }
1804*67e74705SXin Li   } while (type->isVariablyModifiedType());
1805*67e74705SXin Li }
1806*67e74705SXin Li 
EmitVAListRef(const Expr * E)1807*67e74705SXin Li Address CodeGenFunction::EmitVAListRef(const Expr* E) {
1808*67e74705SXin Li   if (getContext().getBuiltinVaListType()->isArrayType())
1809*67e74705SXin Li     return EmitPointerWithAlignment(E);
1810*67e74705SXin Li   return EmitLValue(E).getAddress();
1811*67e74705SXin Li }
1812*67e74705SXin Li 
EmitMSVAListRef(const Expr * E)1813*67e74705SXin Li Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
1814*67e74705SXin Li   return EmitLValue(E).getAddress();
1815*67e74705SXin Li }
1816*67e74705SXin Li 
EmitDeclRefExprDbgValue(const DeclRefExpr * E,llvm::Constant * Init)1817*67e74705SXin Li void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
1818*67e74705SXin Li                                               llvm::Constant *Init) {
1819*67e74705SXin Li   assert (Init && "Invalid DeclRefExpr initializer!");
1820*67e74705SXin Li   if (CGDebugInfo *Dbg = getDebugInfo())
1821*67e74705SXin Li     if (CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
1822*67e74705SXin Li       Dbg->EmitGlobalVariable(E->getDecl(), Init);
1823*67e74705SXin Li }
1824*67e74705SXin Li 
1825*67e74705SXin Li CodeGenFunction::PeepholeProtection
protectFromPeepholes(RValue rvalue)1826*67e74705SXin Li CodeGenFunction::protectFromPeepholes(RValue rvalue) {
1827*67e74705SXin Li   // At the moment, the only aggressive peephole we do in IR gen
1828*67e74705SXin Li   // is trunc(zext) folding, but if we add more, we can easily
1829*67e74705SXin Li   // extend this protection.
1830*67e74705SXin Li 
1831*67e74705SXin Li   if (!rvalue.isScalar()) return PeepholeProtection();
1832*67e74705SXin Li   llvm::Value *value = rvalue.getScalarVal();
1833*67e74705SXin Li   if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
1834*67e74705SXin Li 
1835*67e74705SXin Li   // Just make an extra bitcast.
1836*67e74705SXin Li   assert(HaveInsertPoint());
1837*67e74705SXin Li   llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
1838*67e74705SXin Li                                                   Builder.GetInsertBlock());
1839*67e74705SXin Li 
1840*67e74705SXin Li   PeepholeProtection protection;
1841*67e74705SXin Li   protection.Inst = inst;
1842*67e74705SXin Li   return protection;
1843*67e74705SXin Li }
1844*67e74705SXin Li 
unprotectFromPeepholes(PeepholeProtection protection)1845*67e74705SXin Li void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
1846*67e74705SXin Li   if (!protection.Inst) return;
1847*67e74705SXin Li 
1848*67e74705SXin Li   // In theory, we could try to duplicate the peepholes now, but whatever.
1849*67e74705SXin Li   protection.Inst->eraseFromParent();
1850*67e74705SXin Li }
1851*67e74705SXin Li 
EmitAnnotationCall(llvm::Value * AnnotationFn,llvm::Value * AnnotatedVal,StringRef AnnotationStr,SourceLocation Location)1852*67e74705SXin Li llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
1853*67e74705SXin Li                                                  llvm::Value *AnnotatedVal,
1854*67e74705SXin Li                                                  StringRef AnnotationStr,
1855*67e74705SXin Li                                                  SourceLocation Location) {
1856*67e74705SXin Li   llvm::Value *Args[4] = {
1857*67e74705SXin Li     AnnotatedVal,
1858*67e74705SXin Li     Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
1859*67e74705SXin Li     Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
1860*67e74705SXin Li     CGM.EmitAnnotationLineNo(Location)
1861*67e74705SXin Li   };
1862*67e74705SXin Li   return Builder.CreateCall(AnnotationFn, Args);
1863*67e74705SXin Li }
1864*67e74705SXin Li 
EmitVarAnnotations(const VarDecl * D,llvm::Value * V)1865*67e74705SXin Li void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
1866*67e74705SXin Li   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1867*67e74705SXin Li   // FIXME We create a new bitcast for every annotation because that's what
1868*67e74705SXin Li   // llvm-gcc was doing.
1869*67e74705SXin Li   for (const auto *I : D->specific_attrs<AnnotateAttr>())
1870*67e74705SXin Li     EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
1871*67e74705SXin Li                        Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
1872*67e74705SXin Li                        I->getAnnotation(), D->getLocation());
1873*67e74705SXin Li }
1874*67e74705SXin Li 
EmitFieldAnnotations(const FieldDecl * D,Address Addr)1875*67e74705SXin Li Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
1876*67e74705SXin Li                                               Address Addr) {
1877*67e74705SXin Li   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1878*67e74705SXin Li   llvm::Value *V = Addr.getPointer();
1879*67e74705SXin Li   llvm::Type *VTy = V->getType();
1880*67e74705SXin Li   llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
1881*67e74705SXin Li                                     CGM.Int8PtrTy);
1882*67e74705SXin Li 
1883*67e74705SXin Li   for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
1884*67e74705SXin Li     // FIXME Always emit the cast inst so we can differentiate between
1885*67e74705SXin Li     // annotation on the first field of a struct and annotation on the struct
1886*67e74705SXin Li     // itself.
1887*67e74705SXin Li     if (VTy != CGM.Int8PtrTy)
1888*67e74705SXin Li       V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
1889*67e74705SXin Li     V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation());
1890*67e74705SXin Li     V = Builder.CreateBitCast(V, VTy);
1891*67e74705SXin Li   }
1892*67e74705SXin Li 
1893*67e74705SXin Li   return Address(V, Addr.getAlignment());
1894*67e74705SXin Li }
1895*67e74705SXin Li 
~CGCapturedStmtInfo()1896*67e74705SXin Li CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
1897*67e74705SXin Li 
SanitizerScope(CodeGenFunction * CGF)1898*67e74705SXin Li CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
1899*67e74705SXin Li     : CGF(CGF) {
1900*67e74705SXin Li   assert(!CGF->IsSanitizerScope);
1901*67e74705SXin Li   CGF->IsSanitizerScope = true;
1902*67e74705SXin Li }
1903*67e74705SXin Li 
~SanitizerScope()1904*67e74705SXin Li CodeGenFunction::SanitizerScope::~SanitizerScope() {
1905*67e74705SXin Li   CGF->IsSanitizerScope = false;
1906*67e74705SXin Li }
1907*67e74705SXin Li 
InsertHelper(llvm::Instruction * I,const llvm::Twine & Name,llvm::BasicBlock * BB,llvm::BasicBlock::iterator InsertPt) const1908*67e74705SXin Li void CodeGenFunction::InsertHelper(llvm::Instruction *I,
1909*67e74705SXin Li                                    const llvm::Twine &Name,
1910*67e74705SXin Li                                    llvm::BasicBlock *BB,
1911*67e74705SXin Li                                    llvm::BasicBlock::iterator InsertPt) const {
1912*67e74705SXin Li   LoopStack.InsertHelper(I);
1913*67e74705SXin Li   if (IsSanitizerScope)
1914*67e74705SXin Li     CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
1915*67e74705SXin Li }
1916*67e74705SXin Li 
InsertHelper(llvm::Instruction * I,const llvm::Twine & Name,llvm::BasicBlock * BB,llvm::BasicBlock::iterator InsertPt) const1917*67e74705SXin Li void CGBuilderInserter::InsertHelper(
1918*67e74705SXin Li     llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
1919*67e74705SXin Li     llvm::BasicBlock::iterator InsertPt) const {
1920*67e74705SXin Li   llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
1921*67e74705SXin Li   if (CGF)
1922*67e74705SXin Li     CGF->InsertHelper(I, Name, BB, InsertPt);
1923*67e74705SXin Li }
1924*67e74705SXin Li 
hasRequiredFeatures(const SmallVectorImpl<StringRef> & ReqFeatures,CodeGenModule & CGM,const FunctionDecl * FD,std::string & FirstMissing)1925*67e74705SXin Li static bool hasRequiredFeatures(const SmallVectorImpl<StringRef> &ReqFeatures,
1926*67e74705SXin Li                                 CodeGenModule &CGM, const FunctionDecl *FD,
1927*67e74705SXin Li                                 std::string &FirstMissing) {
1928*67e74705SXin Li   // If there aren't any required features listed then go ahead and return.
1929*67e74705SXin Li   if (ReqFeatures.empty())
1930*67e74705SXin Li     return false;
1931*67e74705SXin Li 
1932*67e74705SXin Li   // Now build up the set of caller features and verify that all the required
1933*67e74705SXin Li   // features are there.
1934*67e74705SXin Li   llvm::StringMap<bool> CallerFeatureMap;
1935*67e74705SXin Li   CGM.getFunctionFeatureMap(CallerFeatureMap, FD);
1936*67e74705SXin Li 
1937*67e74705SXin Li   // If we have at least one of the features in the feature list return
1938*67e74705SXin Li   // true, otherwise return false.
1939*67e74705SXin Li   return std::all_of(
1940*67e74705SXin Li       ReqFeatures.begin(), ReqFeatures.end(), [&](StringRef Feature) {
1941*67e74705SXin Li         SmallVector<StringRef, 1> OrFeatures;
1942*67e74705SXin Li         Feature.split(OrFeatures, "|");
1943*67e74705SXin Li         return std::any_of(OrFeatures.begin(), OrFeatures.end(),
1944*67e74705SXin Li                            [&](StringRef Feature) {
1945*67e74705SXin Li                              if (!CallerFeatureMap.lookup(Feature)) {
1946*67e74705SXin Li                                FirstMissing = Feature.str();
1947*67e74705SXin Li                                return false;
1948*67e74705SXin Li                              }
1949*67e74705SXin Li                              return true;
1950*67e74705SXin Li                            });
1951*67e74705SXin Li       });
1952*67e74705SXin Li }
1953*67e74705SXin Li 
1954*67e74705SXin Li // Emits an error if we don't have a valid set of target features for the
1955*67e74705SXin Li // called function.
checkTargetFeatures(const CallExpr * E,const FunctionDecl * TargetDecl)1956*67e74705SXin Li void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
1957*67e74705SXin Li                                           const FunctionDecl *TargetDecl) {
1958*67e74705SXin Li   // Early exit if this is an indirect call.
1959*67e74705SXin Li   if (!TargetDecl)
1960*67e74705SXin Li     return;
1961*67e74705SXin Li 
1962*67e74705SXin Li   // Get the current enclosing function if it exists. If it doesn't
1963*67e74705SXin Li   // we can't check the target features anyhow.
1964*67e74705SXin Li   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl);
1965*67e74705SXin Li   if (!FD)
1966*67e74705SXin Li     return;
1967*67e74705SXin Li 
1968*67e74705SXin Li   // Grab the required features for the call. For a builtin this is listed in
1969*67e74705SXin Li   // the td file with the default cpu, for an always_inline function this is any
1970*67e74705SXin Li   // listed cpu and any listed features.
1971*67e74705SXin Li   unsigned BuiltinID = TargetDecl->getBuiltinID();
1972*67e74705SXin Li   std::string MissingFeature;
1973*67e74705SXin Li   if (BuiltinID) {
1974*67e74705SXin Li     SmallVector<StringRef, 1> ReqFeatures;
1975*67e74705SXin Li     const char *FeatureList =
1976*67e74705SXin Li         CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
1977*67e74705SXin Li     // Return if the builtin doesn't have any required features.
1978*67e74705SXin Li     if (!FeatureList || StringRef(FeatureList) == "")
1979*67e74705SXin Li       return;
1980*67e74705SXin Li     StringRef(FeatureList).split(ReqFeatures, ",");
1981*67e74705SXin Li     if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
1982*67e74705SXin Li       CGM.getDiags().Report(E->getLocStart(), diag::err_builtin_needs_feature)
1983*67e74705SXin Li           << TargetDecl->getDeclName()
1984*67e74705SXin Li           << CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
1985*67e74705SXin Li 
1986*67e74705SXin Li   } else if (TargetDecl->hasAttr<TargetAttr>()) {
1987*67e74705SXin Li     // Get the required features for the callee.
1988*67e74705SXin Li     SmallVector<StringRef, 1> ReqFeatures;
1989*67e74705SXin Li     llvm::StringMap<bool> CalleeFeatureMap;
1990*67e74705SXin Li     CGM.getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
1991*67e74705SXin Li     for (const auto &F : CalleeFeatureMap) {
1992*67e74705SXin Li       // Only positive features are "required".
1993*67e74705SXin Li       if (F.getValue())
1994*67e74705SXin Li         ReqFeatures.push_back(F.getKey());
1995*67e74705SXin Li     }
1996*67e74705SXin Li     if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
1997*67e74705SXin Li       CGM.getDiags().Report(E->getLocStart(), diag::err_function_needs_feature)
1998*67e74705SXin Li           << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
1999*67e74705SXin Li   }
2000*67e74705SXin Li }
2001*67e74705SXin Li 
EmitSanitizerStatReport(llvm::SanitizerStatKind SSK)2002*67e74705SXin Li void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
2003*67e74705SXin Li   if (!CGM.getCodeGenOpts().SanitizeStats)
2004*67e74705SXin Li     return;
2005*67e74705SXin Li 
2006*67e74705SXin Li   llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
2007*67e74705SXin Li   IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
2008*67e74705SXin Li   CGM.getSanStats().create(IRB, SSK);
2009*67e74705SXin Li }
2010