Coverage Report

Created: 2021-09-21 08:58

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/CodeGen/CodeGenFunction.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This coordinates the per-function state used while generating code.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "CodeGenFunction.h"
14
#include "CGBlocks.h"
15
#include "CGCUDARuntime.h"
16
#include "CGCXXABI.h"
17
#include "CGCleanup.h"
18
#include "CGDebugInfo.h"
19
#include "CGOpenMPRuntime.h"
20
#include "CodeGenModule.h"
21
#include "CodeGenPGO.h"
22
#include "TargetInfo.h"
23
#include "clang/AST/ASTContext.h"
24
#include "clang/AST/ASTLambda.h"
25
#include "clang/AST/Attr.h"
26
#include "clang/AST/Decl.h"
27
#include "clang/AST/DeclCXX.h"
28
#include "clang/AST/Expr.h"
29
#include "clang/AST/StmtCXX.h"
30
#include "clang/AST/StmtObjC.h"
31
#include "clang/Basic/Builtins.h"
32
#include "clang/Basic/CodeGenOptions.h"
33
#include "clang/Basic/TargetInfo.h"
34
#include "clang/CodeGen/CGFunctionInfo.h"
35
#include "clang/Frontend/FrontendDiagnostic.h"
36
#include "llvm/ADT/ArrayRef.h"
37
#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
38
#include "llvm/IR/DataLayout.h"
39
#include "llvm/IR/Dominators.h"
40
#include "llvm/IR/FPEnv.h"
41
#include "llvm/IR/IntrinsicInst.h"
42
#include "llvm/IR/Intrinsics.h"
43
#include "llvm/IR/MDBuilder.h"
44
#include "llvm/IR/Operator.h"
45
#include "llvm/Support/CRC.h"
46
#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
47
#include "llvm/Transforms/Utils/PromoteMemToReg.h"
48
using namespace clang;
49
using namespace CodeGen;
50
51
/// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
52
/// markers.
53
static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
54
378k
                                      const LangOptions &LangOpts) {
55
378k
  if (CGOpts.DisableLifetimeMarkers)
56
7
    return false;
57
58
  // Sanitizers may use markers.
59
378k
  if (CGOpts.SanitizeAddressUseAfterScope ||
60
378k
      
LangOpts.Sanitize.has(SanitizerKind::HWAddress)377k
||
61
378k
      
LangOpts.Sanitize.has(SanitizerKind::Memory)377k
)
62
1.51k
    return true;
63
64
  // For now, only in optimized builds.
65
376k
  return CGOpts.OptimizationLevel != 0;
66
378k
}
67
68
CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
69
    : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
70
      Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
71
              CGBuilderInserterTy(this)),
72
      SanOpts(CGM.getLangOpts().Sanitize), CurFPFeatures(CGM.getLangOpts()),
73
      DebugInfo(CGM.getModuleDebugInfo()), PGO(cgm),
74
      ShouldEmitLifetimeMarkers(
75
378k
          shouldEmitLifetimeMarkers(CGM.getCodeGenOpts(), CGM.getLangOpts())) {
76
378k
  if (!suppressNewContext)
77
351k
    CGM.getCXXABI().getMangleContext().startNewFunction();
78
378k
  EHStack.setCGF(this);
79
80
378k
  SetFastMathFlags(CurFPFeatures);
81
378k
}
82
83
378k
CodeGenFunction::~CodeGenFunction() {
84
378k
  assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
85
86
378k
  if (getLangOpts().OpenMP && 
CurFn70.4k
)
87
70.4k
    CGM.getOpenMPRuntime().functionFinished(*this);
88
89
  // If we have an OpenMPIRBuilder we want to finalize functions (incl.
90
  // outlining etc) at some point. Doing it once the function codegen is done
91
  // seems to be a reasonable spot. We do it here, as opposed to the deletion
92
  // time of the CodeGenModule, because we have to ensure the IR has not yet
93
  // been "emitted" to the outside, thus, modifications are still sensible.
94
378k
  if (CGM.getLangOpts().OpenMPIRBuilder && 
CurFn351
)
95
351
    CGM.getOpenMPRuntime().getOMPBuilder().finalize(CurFn);
96
378k
}
97
98
// Map the LangOption for exception behavior into
99
// the corresponding enum in the IR.
100
llvm::fp::ExceptionBehavior
101
379k
clang::ToConstrainedExceptMD(LangOptions::FPExceptionModeKind Kind) {
102
103
379k
  switch (Kind) {
104
375k
  case LangOptions::FPE_Ignore:  return llvm::fp::ebIgnore;
105
633
  case LangOptions::FPE_MayTrap: return llvm::fp::ebMayTrap;
106
2.87k
  case LangOptions::FPE_Strict:  return llvm::fp::ebStrict;
107
379k
  }
108
0
  llvm_unreachable("Unsupported FP Exception Behavior");
109
0
}
110
111
380k
void CodeGenFunction::SetFastMathFlags(FPOptions FPFeatures) {
112
380k
  llvm::FastMathFlags FMF;
113
380k
  FMF.setAllowReassoc(FPFeatures.getAllowFPReassociate());
114
380k
  FMF.setNoNaNs(FPFeatures.getNoHonorNaNs());
115
380k
  FMF.setNoInfs(FPFeatures.getNoHonorInfs());
116
380k
  FMF.setNoSignedZeros(FPFeatures.getNoSignedZero());
117
380k
  FMF.setAllowReciprocal(FPFeatures.getAllowReciprocal());
118
380k
  FMF.setApproxFunc(FPFeatures.getAllowApproxFunc());
119
380k
  FMF.setAllowContract(FPFeatures.allowFPContractAcrossStatement());
120
380k
  Builder.setFastMathFlags(FMF);
121
380k
}
122
123
CodeGenFunction::CGFPOptionsRAII::CGFPOptionsRAII(CodeGenFunction &CGF,
124
                                                  const Expr *E)
125
194k
    : CGF(CGF) {
126
194k
  ConstructorHelper(E->getFPFeaturesInEffect(CGF.getLangOpts()));
127
194k
}
128
129
CodeGenFunction::CGFPOptionsRAII::CGFPOptionsRAII(CodeGenFunction &CGF,
130
                                                  FPOptions FPFeatures)
131
33.2k
    : CGF(CGF) {
132
33.2k
  ConstructorHelper(FPFeatures);
133
33.2k
}
134
135
227k
void CodeGenFunction::CGFPOptionsRAII::ConstructorHelper(FPOptions FPFeatures) {
136
227k
  OldFPFeatures = CGF.CurFPFeatures;
137
227k
  CGF.CurFPFeatures = FPFeatures;
138
139
227k
  OldExcept = CGF.Builder.getDefaultConstrainedExcept();
140
227k
  OldRounding = CGF.Builder.getDefaultConstrainedRounding();
141
142
227k
  if (OldFPFeatures == FPFeatures)
143
225k
    return;
144
145
2.06k
  FMFGuard.emplace(CGF.Builder);
146
147
2.06k
  llvm::RoundingMode NewRoundingBehavior =
148
2.06k
      static_cast<llvm::RoundingMode>(FPFeatures.getRoundingMode());
149
2.06k
  CGF.Builder.setDefaultConstrainedRounding(NewRoundingBehavior);
150
2.06k
  auto NewExceptionBehavior =
151
2.06k
      ToConstrainedExceptMD(static_cast<LangOptions::FPExceptionModeKind>(
152
2.06k
          FPFeatures.getFPExceptionMode()));
153
2.06k
  CGF.Builder.setDefaultConstrainedExcept(NewExceptionBehavior);
154
155
2.06k
  CGF.SetFastMathFlags(FPFeatures);
156
157
2.06k
  assert((CGF.CurFuncDecl == nullptr || CGF.Builder.getIsFPConstrained() ||
158
2.06k
          isa<CXXConstructorDecl>(CGF.CurFuncDecl) ||
159
2.06k
          isa<CXXDestructorDecl>(CGF.CurFuncDecl) ||
160
2.06k
          (NewExceptionBehavior == llvm::fp::ebIgnore &&
161
2.06k
           NewRoundingBehavior == llvm::RoundingMode::NearestTiesToEven)) &&
162
2.06k
         "FPConstrained should be enabled on entire function");
163
164
8.26k
  auto mergeFnAttrValue = [&](StringRef Name, bool Value) {
165
8.26k
    auto OldValue =
166
8.26k
        CGF.CurFn->getFnAttribute(Name).getValueAsBool();
167
8.26k
    auto NewValue = OldValue & Value;
168
8.26k
    if (OldValue != NewValue)
169
53
      CGF.CurFn->addFnAttr(Name, llvm::toStringRef(NewValue));
170
8.26k
  };
171
2.06k
  mergeFnAttrValue("no-infs-fp-math", FPFeatures.getNoHonorInfs());
172
2.06k
  mergeFnAttrValue("no-nans-fp-math", FPFeatures.getNoHonorNaNs());
173
2.06k
  mergeFnAttrValue("no-signed-zeros-fp-math", FPFeatures.getNoSignedZero());
174
2.06k
  mergeFnAttrValue("unsafe-fp-math", FPFeatures.getAllowFPReassociate() &&
175
2.06k
                                         
FPFeatures.getAllowReciprocal()120
&&
176
2.06k
                                         
FPFeatures.getAllowApproxFunc()72
&&
177
2.06k
                                         
FPFeatures.getNoSignedZero()72
);
178
2.06k
}
179
180
227k
CodeGenFunction::CGFPOptionsRAII::~CGFPOptionsRAII() {
181
227k
  CGF.CurFPFeatures = OldFPFeatures;
182
227k
  CGF.Builder.setDefaultConstrainedExcept(OldExcept);
183
227k
  CGF.Builder.setDefaultConstrainedRounding(OldRounding);
184
227k
}
185
186
41.6k
LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
187
41.6k
  LValueBaseInfo BaseInfo;
188
41.6k
  TBAAAccessInfo TBAAInfo;
189
41.6k
  CharUnits Alignment = CGM.getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo);
190
41.6k
  return LValue::MakeAddr(Address(V, Alignment), T, getContext(), BaseInfo,
191
41.6k
                          TBAAInfo);
192
41.6k
}
193
194
/// Given a value of type T* that may not be to a complete object,
195
/// construct an l-value with the natural pointee alignment of T.
196
LValue
197
63.2k
CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
198
63.2k
  LValueBaseInfo BaseInfo;
199
63.2k
  TBAAAccessInfo TBAAInfo;
200
63.2k
  CharUnits Align = CGM.getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo,
201
63.2k
                                                /* forPointeeType= */ true);
202
63.2k
  return MakeAddrLValue(Address(V, Align), T, BaseInfo, TBAAInfo);
203
63.2k
}
204
205
206
1.32M
llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
207
1.32M
  return CGM.getTypes().ConvertTypeForMem(T);
208
1.32M
}
209
210
4.46M
llvm::Type *CodeGenFunction::ConvertType(QualType T) {
211
4.46M
  return CGM.getTypes().ConvertType(T);
212
4.46M
}
213
214
8.07M
TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
215
8.07M
  type = type.getCanonicalType();
216
8.07M
  while (true) {
217
8.07M
    switch (type->getTypeClass()) {
218
0
#define TYPE(name, parent)
219
0
#define ABSTRACT_TYPE(name, parent)
220
0
#define NON_CANONICAL_TYPE(name, parent) case Type::name:
221
0
#define DEPENDENT_TYPE(name, parent) case Type::name:
222
0
#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
223
0
#include "clang/AST/TypeNodes.inc"
224
0
      llvm_unreachable("non-canonical or dependent type in IR-generation");
225
226
0
    case Type::Auto:
227
0
    case Type::DeducedTemplateSpecialization:
228
0
      llvm_unreachable("undeduced type in IR-generation");
229
230
    // Various scalar types.
231
4.39M
    case Type::Builtin:
232
6.65M
    case Type::Pointer:
233
6.65M
    case Type::BlockPointer:
234
6.84M
    case Type::LValueReference:
235
6.90M
    case Type::RValueReference:
236
6.90M
    case Type::MemberPointer:
237
7.67M
    case Type::Vector:
238
7.68M
    case Type::ExtVector:
239
7.68M
    case Type::ConstantMatrix:
240
7.68M
    case Type::FunctionProto:
241
7.68M
    case Type::FunctionNoProto:
242
7.69M
    case Type::Enum:
243
7.82M
    case Type::ObjCObjectPointer:
244
7.82M
    case Type::Pipe:
245
7.83M
    case Type::ExtInt:
246
7.83M
      return TEK_Scalar;
247
248
    // Complexes.
249
7.70k
    case Type::Complex:
250
7.70k
      return TEK_Complex;
251
252
    // Arrays, records, and Objective-C objects.
253
5.58k
    case Type::ConstantArray:
254
5.58k
    case Type::IncompleteArray:
255
5.60k
    case Type::VariableArray:
256
233k
    case Type::Record:
257
233k
    case Type::ObjCObject:
258
233k
    case Type::ObjCInterface:
259
233k
      return TEK_Aggregate;
260
261
    // We operate on atomic values according to their underlying type.
262
314
    case Type::Atomic:
263
314
      type = cast<AtomicType>(type)->getValueType();
264
314
      continue;
265
8.07M
    }
266
0
    llvm_unreachable("unknown type kind!");
267
0
  }
268
8.07M
}
269
270
377k
llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
271
  // For cleanliness, we try to avoid emitting the return block for
272
  // simple cases.
273
377k
  llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
274
275
377k
  if (CurBB) {
276
163k
    assert(!CurBB->getTerminator() && "Unexpected terminated block.");
277
278
    // We have a valid insert point, reuse it if it is empty or there are no
279
    // explicit jumps to the return block.
280
163k
    if (CurBB->empty() || 
ReturnBlock.getBlock()->use_empty()135k
) {
281
163k
      ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
282
163k
      delete ReturnBlock.getBlock();
283
163k
      ReturnBlock = JumpDest();
284
163k
    } else
285
30
      EmitBlock(ReturnBlock.getBlock());
286
163k
    return llvm::DebugLoc();
287
163k
  }
288
289
  // Otherwise, if the return block is the target of a single direct
290
  // branch then we can just put the code in that block instead. This
291
  // cleans up functions which started with a unified return block.
292
213k
  if (ReturnBlock.getBlock()->hasOneUse()) {
293
210k
    llvm::BranchInst *BI =
294
210k
      dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
295
210k
    if (BI && 
BI->isUnconditional()210k
&&
296
210k
        
BI->getSuccessor(0) == ReturnBlock.getBlock()210k
) {
297
      // Record/return the DebugLoc of the simple 'return' expression to be used
298
      // later by the actual 'ret' instruction.
299
210k
      llvm::DebugLoc Loc = BI->getDebugLoc();
300
210k
      Builder.SetInsertPoint(BI->getParent());
301
210k
      BI->eraseFromParent();
302
210k
      delete ReturnBlock.getBlock();
303
210k
      ReturnBlock = JumpDest();
304
210k
      return Loc;
305
210k
    }
306
210k
  }
307
308
  // FIXME: We are at an unreachable point, there is no reason to emit the block
309
  // unless it has uses. However, we still need a place to put the debug
310
  // region.end for now.
311
312
3.26k
  EmitBlock(ReturnBlock.getBlock());
313
3.26k
  return llvm::DebugLoc();
314
213k
}
315
316
1.50M
static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
317
1.50M
  if (!BB) 
return1.50M
;
318
8.44k
  if (!BB->use_empty())
319
8.43k
    return CGF.CurFn->getBasicBlockList().push_back(BB);
320
8
  delete BB;
321
8
}
322
323
377k
void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
324
377k
  assert(BreakContinueStack.empty() &&
325
377k
         "mismatched push/pop in break/continue stack!");
326
327
377k
  bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
328
377k
    && 
NumSimpleReturnExprs == NumReturnExprs14.5k
329
377k
    && 
ReturnBlock.getBlock()->use_empty()13.3k
;
330
  // Usually the return expression is evaluated before the cleanup
331
  // code.  If the function contains only a simple return statement,
332
  // such as a constant, the location before the cleanup code becomes
333
  // the last useful breakpoint in the function, because the simple
334
  // return expression will be evaluated after the cleanup code. To be
335
  // safe, set the debug location for cleanup code to the location of
336
  // the return statement.  Otherwise the cleanup code should be at the
337
  // end of the function's lexical scope.
338
  //
339
  // If there are multiple branches to the return block, the branch
340
  // instructions will get the location of the return statements and
341
  // all will be fine.
342
377k
  if (CGDebugInfo *DI = getDebugInfo()) {
343
102k
    if (OnlySimpleReturnStmts)
344
617
      DI->EmitLocation(Builder, LastStopPoint);
345
101k
    else
346
101k
      DI->EmitLocation(Builder, EndLoc);
347
102k
  }
348
349
  // Pop any cleanups that might have been associated with the
350
  // parameters.  Do this in whatever block we're currently in; it's
351
  // important to do this before we enter the return block or return
352
  // edges will be *really* confused.
353
377k
  bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
354
377k
  bool HasOnlyLifetimeMarkers =
355
377k
      HasCleanups && 
EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth)8.79k
;
356
377k
  bool EmitRetDbgLoc = !HasCleanups || 
HasOnlyLifetimeMarkers8.79k
;
357
377k
  if (HasCleanups) {
358
    // Make sure the line table doesn't jump back into the body for
359
    // the ret after it's been at EndLoc.
360
8.79k
    Optional<ApplyDebugLocation> AL;
361
8.79k
    if (CGDebugInfo *DI = getDebugInfo()) {
362
1.87k
      if (OnlySimpleReturnStmts)
363
617
        DI->EmitLocation(Builder, EndLoc);
364
1.25k
      else
365
        // We may not have a valid end location. Try to apply it anyway, and
366
        // fall back to an artificial location if needed.
367
1.25k
        AL = ApplyDebugLocation::CreateDefaultArtificial(*this, EndLoc);
368
1.87k
    }
369
370
8.79k
    PopCleanupBlocks(PrologueCleanupDepth);
371
8.79k
  }
372
373
  // Emit function epilog (to return).
374
377k
  llvm::DebugLoc Loc = EmitReturnBlock();
375
376
377k
  if (ShouldInstrumentFunction()) {
377
15
    if (CGM.getCodeGenOpts().InstrumentFunctions)
378
10
      CurFn->addFnAttr("instrument-function-exit", "__cyg_profile_func_exit");
379
15
    if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
380
4
      CurFn->addFnAttr("instrument-function-exit-inlined",
381
4
                       "__cyg_profile_func_exit");
382
15
  }
383
384
377k
  if (ShouldSkipSanitizerInstrumentation())
385
6
    CurFn->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation);
386
387
  // Emit debug descriptor for function end.
388
377k
  if (CGDebugInfo *DI = getDebugInfo())
389
102k
    DI->EmitFunctionEnd(Builder, CurFn);
390
391
  // Reset the debug location to that of the simple 'return' expression, if any
392
  // rather than that of the end of the function's scope '}'.
393
377k
  ApplyDebugLocation AL(*this, Loc);
394
377k
  EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
395
377k
  EmitEndEHSpec(CurCodeDecl);
396
397
377k
  assert(EHStack.empty() &&
398
377k
         "did not remove all scopes from cleanup stack!");
399
400
  // If someone did an indirect goto, emit the indirect goto block at the end of
401
  // the function.
402
377k
  if (IndirectBranch) {
403
35
    EmitBlock(IndirectBranch->getParent());
404
35
    Builder.ClearInsertionPoint();
405
35
  }
406
407
  // If some of our locals escaped, insert a call to llvm.localescape in the
408
  // entry block.
409
377k
  if (!EscapedLocals.empty()) {
410
    // Invert the map from local to index into a simple vector. There should be
411
    // no holes.
412
38
    SmallVector<llvm::Value *, 4> EscapeArgs;
413
38
    EscapeArgs.resize(EscapedLocals.size());
414
38
    for (auto &Pair : EscapedLocals)
415
46
      EscapeArgs[Pair.second] = Pair.first;
416
38
    llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
417
38
        &CGM.getModule(), llvm::Intrinsic::localescape);
418
38
    CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
419
38
  }
420
421
  // Remove the AllocaInsertPt instruction, which is just a convenience for us.
422
377k
  llvm::Instruction *Ptr = AllocaInsertPt;
423
377k
  AllocaInsertPt = nullptr;
424
377k
  Ptr->eraseFromParent();
425
426
  // If someone took the address of a label but never did an indirect goto, we
427
  // made a zero entry PHI node, which is illegal, zap it now.
428
377k
  if (IndirectBranch) {
429
35
    llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
430
35
    if (PN->getNumIncomingValues() == 0) {
431
15
      PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
432
15
      PN->eraseFromParent();
433
15
    }
434
35
  }
435
436
377k
  EmitIfUsed(*this, EHResumeBlock);
437
377k
  EmitIfUsed(*this, TerminateLandingPad);
438
377k
  EmitIfUsed(*this, TerminateHandler);
439
377k
  EmitIfUsed(*this, UnreachableBlock);
440
441
377k
  for (const auto &FuncletAndParent : TerminateFunclets)
442
31
    EmitIfUsed(*this, FuncletAndParent.second);
443
444
377k
  if (CGM.getCodeGenOpts().EmitDeclMetadata)
445
24.2k
    EmitDeclMetadata();
446
447
377k
  for (const auto &R : DeferredReplacements) {
448
103
    if (llvm::Value *Old = R.first) {
449
102
      Old->replaceAllUsesWith(R.second);
450
102
      cast<llvm::Instruction>(Old)->eraseFromParent();
451
102
    }
452
103
  }
453
377k
  DeferredReplacements.clear();
454
455
  // Eliminate CleanupDestSlot alloca by replacing it with SSA values and
456
  // PHIs if the current function is a coroutine. We don't do it for all
457
  // functions as it may result in slight increase in numbers of instructions
458
  // if compiled with no optimizations. We do it for coroutine as the lifetime
459
  // of CleanupDestSlot alloca make correct coroutine frame building very
460
  // difficult.
461
377k
  if (NormalCleanupDest.isValid() && 
isCoroutine()297
) {
462
55
    llvm::DominatorTree DT(*CurFn);
463
55
    llvm::PromoteMemToReg(
464
55
        cast<llvm::AllocaInst>(NormalCleanupDest.getPointer()), DT);
465
55
    NormalCleanupDest = Address::invalid();
466
55
  }
467
468
  // Scan function arguments for vector width.
469
377k
  for (llvm::Argument &A : CurFn->args())
470
826k
    if (auto *VT = dyn_cast<llvm::VectorType>(A.getType()))
471
298k
      LargestVectorWidth =
472
298k
          std::max((uint64_t)LargestVectorWidth,
473
298k
                   VT->getPrimitiveSizeInBits().getKnownMinSize());
474
475
  // Update vector width based on return type.
476
377k
  if (auto *VT = dyn_cast<llvm::VectorType>(CurFn->getReturnType()))
477
94.3k
    LargestVectorWidth =
478
94.3k
        std::max((uint64_t)LargestVectorWidth,
479
94.3k
                 VT->getPrimitiveSizeInBits().getKnownMinSize());
480
481
  // Add the required-vector-width attribute. This contains the max width from:
482
  // 1. min-vector-width attribute used in the source program.
483
  // 2. Any builtins used that have a vector width specified.
484
  // 3. Values passed in and out of inline assembly.
485
  // 4. Width of vector arguments and return types for this function.
486
  // 5. Width of vector aguments and return types for functions called by this
487
  //    function.
488
377k
  CurFn->addFnAttr("min-legal-vector-width", llvm::utostr(LargestVectorWidth));
489
490
  // Add vscale_range attribute if appropriate.
491
377k
  Optional<std::pair<unsigned, unsigned>> VScaleRange =
492
377k
      getContext().getTargetInfo().getVScaleRange(getLangOpts());
493
377k
  if (VScaleRange) {
494
29.6k
    CurFn->addFnAttr(llvm::Attribute::getWithVScaleRangeArgs(
495
29.6k
        getLLVMContext(), VScaleRange.getValue().first,
496
29.6k
        VScaleRange.getValue().second));
497
29.6k
  }
498
499
  // If we generated an unreachable return block, delete it now.
500
377k
  if (ReturnBlock.isValid() && 
ReturnBlock.getBlock()->use_empty()3.29k
) {
501
1.43k
    Builder.ClearInsertionPoint();
502
1.43k
    ReturnBlock.getBlock()->eraseFromParent();
503
1.43k
  }
504
377k
  if (ReturnValue.isValid()) {
505
193k
    auto *RetAlloca = dyn_cast<llvm::AllocaInst>(ReturnValue.getPointer());
506
193k
    if (RetAlloca && 
RetAlloca->use_empty()190k
) {
507
176k
      RetAlloca->eraseFromParent();
508
176k
      ReturnValue = Address::invalid();
509
176k
    }
510
193k
  }
511
377k
}
512
513
/// ShouldInstrumentFunction - Return true if the current function should be
514
/// instrumented with __cyg_profile_func_* calls
515
754k
bool CodeGenFunction::ShouldInstrumentFunction() {
516
754k
  if (!CGM.getCodeGenOpts().InstrumentFunctions &&
517
754k
      
!CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining754k
&&
518
754k
      
!CGM.getCodeGenOpts().InstrumentFunctionEntryBare754k
)
519
754k
    return false;
520
40
  if (!CurFuncDecl || 
CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()36
)
521
10
    return false;
522
30
  return true;
523
40
}
524
525
377k
bool CodeGenFunction::ShouldSkipSanitizerInstrumentation() {
526
377k
  if (!CurFuncDecl)
527
15.4k
    return false;
528
361k
  return CurFuncDecl->hasAttr<DisableSanitizerInstrumentationAttr>();
529
377k
}
530
531
/// ShouldXRayInstrument - Return true if the current function should be
532
/// instrumented with XRay nop sleds.
533
754k
bool CodeGenFunction::ShouldXRayInstrumentFunction() const {
534
754k
  return CGM.getCodeGenOpts().XRayInstrumentFunctions;
535
754k
}
536
537
/// AlwaysEmitXRayCustomEvents - Return true if we should emit IR for calls to
538
/// the __xray_customevent(...) builtin calls, when doing XRay instrumentation.
539
2
bool CodeGenFunction::AlwaysEmitXRayCustomEvents() const {
540
2
  return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
541
2
         (CGM.getCodeGenOpts().XRayAlwaysEmitCustomEvents ||
542
2
          CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
543
1
              XRayInstrKind::Custom);
544
2
}
545
546
2
bool CodeGenFunction::AlwaysEmitXRayTypedEvents() const {
547
2
  return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
548
2
         (CGM.getCodeGenOpts().XRayAlwaysEmitTypedEvents ||
549
2
          CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
550
1
              XRayInstrKind::Typed);
551
2
}
552
553
llvm::Constant *
554
CodeGenFunction::EncodeAddrForUseInPrologue(llvm::Function *F,
555
111
                                            llvm::Constant *Addr) {
556
  // Addresses stored in prologue data can't require run-time fixups and must
557
  // be PC-relative. Run-time fixups are undesirable because they necessitate
558
  // writable text segments, which are unsafe. And absolute addresses are
559
  // undesirable because they break PIE mode.
560
561
  // Add a layer of indirection through a private global. Taking its address
562
  // won't result in a run-time fixup, even if Addr has linkonce_odr linkage.
563
111
  auto *GV = new llvm::GlobalVariable(CGM.getModule(), Addr->getType(),
564
111
                                      /*isConstant=*/true,
565
111
                                      llvm::GlobalValue::PrivateLinkage, Addr);
566
567
  // Create a PC-relative address.
568
111
  auto *GOTAsInt = llvm::ConstantExpr::getPtrToInt(GV, IntPtrTy);
569
111
  auto *FuncAsInt = llvm::ConstantExpr::getPtrToInt(F, IntPtrTy);
570
111
  auto *PCRelAsInt = llvm::ConstantExpr::getSub(GOTAsInt, FuncAsInt);
571
111
  return (IntPtrTy == Int32Ty)
572
111
             ? 
PCRelAsInt70
573
111
             : 
llvm::ConstantExpr::getTrunc(PCRelAsInt, Int32Ty)41
;
574
111
}
575
576
llvm::Value *
577
CodeGenFunction::DecodeAddrUsedInPrologue(llvm::Value *F,
578
8
                                          llvm::Value *EncodedAddr) {
579
  // Reconstruct the address of the global.
580
8
  auto *PCRelAsInt = Builder.CreateSExt(EncodedAddr, IntPtrTy);
581
8
  auto *FuncAsInt = Builder.CreatePtrToInt(F, IntPtrTy, "func_addr.int");
582
8
  auto *GOTAsInt = Builder.CreateAdd(PCRelAsInt, FuncAsInt, "global_addr.int");
583
8
  auto *GOTAddr = Builder.CreateIntToPtr(GOTAsInt, Int8PtrPtrTy, "global_addr");
584
585
  // Load the original pointer through the global.
586
8
  return Builder.CreateLoad(Address(GOTAddr, getPointerAlign()),
587
8
                            "decoded_addr");
588
8
}
589
590
void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
591
                                               llvm::Function *Fn)
592
2.00k
{
593
2.00k
  if (!FD->hasAttr<OpenCLKernelAttr>())
594
1.50k
    return;
595
596
493
  llvm::LLVMContext &Context = getLLVMContext();
597
598
493
  CGM.GenOpenCLArgMetadata(Fn, FD, this);
599
600
493
  if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
601
2
    QualType HintQTy = A->getTypeHint();
602
2
    const ExtVectorType *HintEltQTy = HintQTy->getAs<ExtVectorType>();
603
2
    bool IsSignedInteger =
604
2
        HintQTy->isSignedIntegerType() ||
605
2
        
(1
HintEltQTy1
&&
HintEltQTy->getElementType()->isSignedIntegerType()1
);
606
2
    llvm::Metadata *AttrMDArgs[] = {
607
2
        llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
608
2
            CGM.getTypes().ConvertType(A->getTypeHint()))),
609
2
        llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
610
2
            llvm::IntegerType::get(Context, 32),
611
2
            llvm::APInt(32, (uint64_t)(IsSignedInteger ? 
11
:
01
))))};
612
2
    Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs));
613
2
  }
614
615
493
  if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
616
1
    llvm::Metadata *AttrMDArgs[] = {
617
1
        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
618
1
        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
619
1
        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
620
1
    Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs));
621
1
  }
622
623
493
  if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
624
7
    llvm::Metadata *AttrMDArgs[] = {
625
7
        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
626
7
        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
627
7
        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
628
7
    Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs));
629
7
  }
630
631
493
  if (const OpenCLIntelReqdSubGroupSizeAttr *A =
632
493
          FD->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
633
1
    llvm::Metadata *AttrMDArgs[] = {
634
1
        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getSubGroupSize()))};
635
1
    Fn->setMetadata("intel_reqd_sub_group_size",
636
1
                    llvm::MDNode::get(Context, AttrMDArgs));
637
1
  }
638
493
}
639
640
/// Determine whether the function F ends with a return stmt.
641
183k
static bool endsWithReturn(const Decl* F) {
642
183k
  const Stmt *Body = nullptr;
643
183k
  if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
644
141k
    Body = FD->getBody();
645
41.2k
  else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
646
1.23k
    Body = OMD->getBody();
647
648
183k
  if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
649
142k
    auto LastStmt = CS->body_rbegin();
650
142k
    if (LastStmt != CS->body_rend())
651
95.7k
      return isa<ReturnStmt>(*LastStmt);
652
142k
  }
653
87.4k
  return false;
654
183k
}
655
656
337
void CodeGenFunction::markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn) {
657
337
  if (SanOpts.has(SanitizerKind::Thread)) {
658
4
    Fn->addFnAttr("sanitize_thread_no_checking_at_run_time");
659
4
    Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
660
4
  }
661
337
}
662
663
/// Check if the return value of this function requires sanitization.
664
592k
bool CodeGenFunction::requiresReturnValueCheck() const {
665
592k
  return requiresReturnValueNullabilityCheck() ||
666
592k
         
(592k
SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)592k
&&
CurCodeDecl108
&&
667
592k
          
CurCodeDecl->getAttr<ReturnsNonNullAttr>()108
);
668
592k
}
669
670
35
static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx) {
671
35
  auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
672
35
  if (!MD || 
!MD->getDeclName().getAsIdentifierInfo()3
||
673
35
      
!MD->getDeclName().getAsIdentifierInfo()->isStr("allocate")3
||
674
35
      
(2
MD->getNumParams() != 12
&&
MD->getNumParams() != 21
))
675
33
    return false;
676
677
2
  if (MD->parameters()[0]->getType().getCanonicalType() != Ctx.getSizeType())
678
0
    return false;
679
680
2
  if (MD->getNumParams() == 2) {
681
1
    auto *PT = MD->parameters()[1]->getType()->getAs<PointerType>();
682
1
    if (!PT || !PT->isVoidPointerType() ||
683
1
        !PT->getPointeeType().isConstQualified())
684
0
      return false;
685
1
  }
686
687
2
  return true;
688
2
}
689
690
/// Return the UBSan prologue signature for \p FD if one is available.
691
static llvm::Constant *getPrologueSignature(CodeGenModule &CGM,
692
204
                                            const FunctionDecl *FD) {
693
204
  if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
694
99
    if (!MD->isStatic())
695
93
      return nullptr;
696
111
  return CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM);
697
204
}
698
699
void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
700
                                    llvm::Function *Fn,
701
                                    const CGFunctionInfo &FnInfo,
702
                                    const FunctionArgList &Args,
703
                                    SourceLocation Loc,
704
377k
                                    SourceLocation StartLoc) {
705
377k
  assert(!CurFn &&
706
377k
         "Do not use a CodeGenFunction object for more than one function");
707
708
0
  const Decl *D = GD.getDecl();
709
710
377k
  DidCallStackSave = false;
711
377k
  CurCodeDecl = D;
712
377k
  const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
713
377k
  if (FD && 
FD->usesSEHTry()333k
)
714
109
    CurSEHParent = FD;
715
377k
  CurFuncDecl = (D ? 
D->getNonClosureContext()368k
:
nullptr8.96k
);
716
377k
  FnRetTy = RetTy;
717
377k
  CurFn = Fn;
718
377k
  CurFnInfo = &FnInfo;
719
377k
  assert(CurFn->isDeclaration() && "Function already has body?");
720
721
  // If this function is ignored for any of the enabled sanitizers,
722
  // disable the sanitizer for the function.
723
377k
  do {
724
377k
#define SANITIZER(NAME, ID)                                                    \
725
994k
  if (
SanOpts.empty()622k
) \
726
994k
    
break372k
; \
727
994k
  
if (249k
SanOpts.has(SanitizerKind::ID)249k
) \
728
249k
    
if (7.90k
CGM.isInNoSanitizeList(SanitizerKind::ID, Fn, Loc)7.90k
) \
729
7.90k
      
SanOpts.set(SanitizerKind::ID, false)55
;
730
731
377k
#include "clang/Basic/Sanitizers.def"
732
249k
#undef SANITIZER
733
249k
  } while (
04.52k
);
734
735
377k
  if (D) {
736
368k
    bool NoSanitizeCoverage = false;
737
738
368k
    for (auto Attr : D->specific_attrs<NoSanitizeAttr>()) {
739
      // Apply the no_sanitize* attributes to SanOpts.
740
1.09k
      SanitizerMask mask = Attr->getMask();
741
1.09k
      SanOpts.Mask &= ~mask;
742
1.09k
      if (mask & SanitizerKind::Address)
743
65
        SanOpts.set(SanitizerKind::KernelAddress, false);
744
1.09k
      if (mask & SanitizerKind::KernelAddress)
745
5
        SanOpts.set(SanitizerKind::Address, false);
746
1.09k
      if (mask & SanitizerKind::HWAddress)
747
5
        SanOpts.set(SanitizerKind::KernelHWAddress, false);
748
1.09k
      if (mask & SanitizerKind::KernelHWAddress)
749
5
        SanOpts.set(SanitizerKind::HWAddress, false);
750
751
      // SanitizeCoverage is not handled by SanOpts.
752
1.09k
      if (Attr->hasCoverage())
753
24
        NoSanitizeCoverage = true;
754
1.09k
    }
755
756
368k
    if (NoSanitizeCoverage && 
CGM.getCodeGenOpts().hasSanitizeCoverage()24
)
757
24
      Fn->addFnAttr(llvm::Attribute::NoSanitizeCoverage);
758
368k
  }
759
760
  // Apply sanitizer attributes to the function.
761
377k
  if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
762
1.09k
    Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
763
377k
  if (SanOpts.hasOneOf(SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress))
764
54
    Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
765
377k
  if (SanOpts.has(SanitizerKind::MemTag))
766
37
    Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
767
377k
  if (SanOpts.has(SanitizerKind::Thread))
768
79
    Fn->addFnAttr(llvm::Attribute::SanitizeThread);
769
377k
  if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory))
770
389
    Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
771
377k
  if (SanOpts.has(SanitizerKind::SafeStack))
772
14
    Fn->addFnAttr(llvm::Attribute::SafeStack);
773
377k
  if (SanOpts.has(SanitizerKind::ShadowCallStack))
774
3
    Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
775
776
  // Apply fuzzing attribute to the function.
777
377k
  if (SanOpts.hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink))
778
2
    Fn->addFnAttr(llvm::Attribute::OptForFuzzing);
779
780
  // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize,
781
  // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time.
782
377k
  if (SanOpts.has(SanitizerKind::Thread)) {
783
79
    if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
784
3
      IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
785
3
      if (OMD->getMethodFamily() == OMF_dealloc ||
786
3
          
OMD->getMethodFamily() == OMF_initialize2
||
787
3
          
(1
OMD->getSelector().isUnarySelector()1
&&
II->isStr(".cxx_destruct")1
)) {
788
3
        markAsIgnoreThreadCheckingAtRuntime(Fn);
789
3
      }
790
3
    }
791
79
  }
792
793
  // Ignore unrelated casts in STL allocate() since the allocator must cast
794
  // from void* to T* before object initialization completes. Don't match on the
795
  // namespace because not all allocators are in std::
796
377k
  if (D && 
SanOpts.has(SanitizerKind::CFIUnrelatedCast)368k
) {
797
35
    if (matchesStlAllocatorFn(D, getContext()))
798
2
      SanOpts.Mask &= ~SanitizerKind::CFIUnrelatedCast;
799
35
  }
800
801
  // Ignore null checks in coroutine functions since the coroutines passes
802
  // are not aware of how to move the extra UBSan instructions across the split
803
  // coroutine boundaries.
804
377k
  if (D && 
SanOpts.has(SanitizerKind::Null)368k
)
805
249
    if (FD && FD->getBody() &&
806
249
        FD->getBody()->getStmtClass() == Stmt::CoroutineBodyStmtClass)
807
1
      SanOpts.Mask &= ~SanitizerKind::Null;
808
809
  // Apply xray attributes to the function (as a string, for now)
810
377k
  bool AlwaysXRayAttr = false;
811
377k
  if (const auto *XRayAttr = D ? D->getAttr<XRayInstrumentAttr>() : nullptr) {
812
86
    if (CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
813
86
            XRayInstrKind::FunctionEntry) ||
814
86
        CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
815
82
            XRayInstrKind::FunctionExit)) {
816
82
      if (XRayAttr->alwaysXRayInstrument() && 
ShouldXRayInstrumentFunction()45
) {
817
38
        Fn->addFnAttr("function-instrument", "xray-always");
818
38
        AlwaysXRayAttr = true;
819
38
      }
820
82
      if (XRayAttr->neverXRayInstrument())
821
37
        Fn->addFnAttr("function-instrument", "xray-never");
822
82
      if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>())
823
1
        if (ShouldXRayInstrumentFunction())
824
1
          Fn->addFnAttr("xray-log-args",
825
1
                        llvm::utostr(LogArgs->getArgumentCount()));
826
82
    }
827
377k
  } else {
828
377k
    if (ShouldXRayInstrumentFunction() && 
!CGM.imbueXRayAttrs(Fn, Loc)31
)
829
19
      Fn->addFnAttr(
830
19
          "xray-instruction-threshold",
831
19
          llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
832
377k
  }
833
834
377k
  if (ShouldXRayInstrumentFunction()) {
835
103
    if (CGM.getCodeGenOpts().XRayIgnoreLoops)
836
1
      Fn->addFnAttr("xray-ignore-loops");
837
838
103
    if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
839
103
            XRayInstrKind::FunctionExit))
840
6
      Fn->addFnAttr("xray-skip-exit");
841
842
103
    if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
843
103
            XRayInstrKind::FunctionEntry))
844
6
      Fn->addFnAttr("xray-skip-entry");
845
846
103
    auto FuncGroups = CGM.getCodeGenOpts().XRayTotalFunctionGroups;
847
103
    if (FuncGroups > 1) {
848
15
      auto FuncName = llvm::makeArrayRef<uint8_t>(
849
15
          CurFn->getName().bytes_begin(), CurFn->getName().bytes_end());
850
15
      auto Group = crc32(FuncName) % FuncGroups;
851
15
      if (Group != CGM.getCodeGenOpts().XRaySelectedFunctionGroup &&
852
15
          
!AlwaysXRayAttr10
)
853
8
        Fn->addFnAttr("function-instrument", "xray-never");
854
15
    }
855
103
  }
856
857
377k
  if (CGM.getCodeGenOpts().getProfileInstr() != CodeGenOptions::ProfileNone)
858
479
    if (CGM.isProfileInstrExcluded(Fn, Loc))
859
4
      Fn->addFnAttr(llvm::Attribute::NoProfile);
860
861
377k
  unsigned Count, Offset;
862
377k
  if (const auto *Attr =
863
377k
          D ? D->getAttr<PatchableFunctionEntryAttr>() : nullptr) {
864
14
    Count = Attr->getCount();
865
14
    Offset = Attr->getOffset();
866
377k
  } else {
867
377k
    Count = CGM.getCodeGenOpts().PatchableFunctionEntryCount;
868
377k
    Offset = CGM.getCodeGenOpts().PatchableFunctionEntryOffset;
869
377k
  }
870
377k
  if (Count && 
Offset <= Count11
) {
871
11
    Fn->addFnAttr("patchable-function-entry", std::to_string(Count - Offset));
872
11
    if (Offset)
873
4
      Fn->addFnAttr("patchable-function-prefix", std::to_string(Offset));
874
11
  }
875
876
  // Add no-jump-tables value.
877
377k
  if (CGM.getCodeGenOpts().NoUseJumpTables)
878
1
    Fn->addFnAttr("no-jump-tables", "true");
879
880
  // Add no-inline-line-tables value.
881
377k
  if (CGM.getCodeGenOpts().NoInlineLineTables)
882
4
    Fn->addFnAttr("no-inline-line-tables");
883
884
  // Add profile-sample-accurate value.
885
377k
  if (CGM.getCodeGenOpts().ProfileSampleAccurate)
886
2
    Fn->addFnAttr("profile-sample-accurate");
887
888
377k
  if (!CGM.getCodeGenOpts().SampleProfileFile.empty())
889
25
    Fn->addFnAttr("use-sample-profile");
890
891
377k
  if (D && 
D->hasAttr<CFICanonicalJumpTableAttr>()368k
)
892
2
    Fn->addFnAttr("cfi-canonical-jump-table");
893
894
377k
  if (D && 
D->hasAttr<NoProfileFunctionAttr>()368k
)
895
4
    Fn->addFnAttr(llvm::Attribute::NoProfile);
896
897
377k
  if (FD && 
getLangOpts().OpenCL333k
) {
898
    // Add metadata for a kernel function.
899
2.00k
    EmitOpenCLKernelMetadata(FD, Fn);
900
2.00k
  }
901
902
  // If we are checking function types, emit a function type signature as
903
  // prologue data.
904
377k
  if (FD && 
getLangOpts().CPlusPlus333k
&&
SanOpts.has(SanitizerKind::Function)188k
) {
905
204
    if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) {
906
      // Remove any (C++17) exception specifications, to allow calling e.g. a
907
      // noexcept function through a non-noexcept pointer.
908
111
      auto ProtoTy = getContext().getFunctionTypeWithExceptionSpec(
909
111
          FD->getType(), EST_None);
910
111
      llvm::Constant *FTRTTIConst =
911
111
          CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true);
912
111
      llvm::Constant *FTRTTIConstEncoded =
913
111
          EncodeAddrForUseInPrologue(Fn, FTRTTIConst);
914
111
      llvm::Constant *PrologueStructElems[] = {PrologueSig, FTRTTIConstEncoded};
915
111
      llvm::Constant *PrologueStructConst =
916
111
          llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
917
111
      Fn->setPrologueData(PrologueStructConst);
918
111
    }
919
204
  }
920
921
  // If we're checking nullability, we need to know whether we can check the
922
  // return value. Initialize the flag to 'true' and refine it in EmitParmDecl.
923
377k
  if (SanOpts.has(SanitizerKind::NullabilityReturn)) {
924
60
    auto Nullability = FnRetTy->getNullability(getContext());
925
60
    if (Nullability && 
*Nullability == NullabilityKind::NonNull17
) {
926
15
      if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
927
15
            
CurCodeDecl1
&&
CurCodeDecl->getAttr<ReturnsNonNullAttr>()1
))
928
14
        RetValNullabilityPrecondition =
929
14
            llvm::ConstantInt::getTrue(getLLVMContext());
930
15
    }
931
60
  }
932
933
  // If we're in C++ mode and the function name is "main", it is guaranteed
934
  // to be norecurse by the standard (3.6.1.3 "The function main shall not be
935
  // used within a program").
936
  //
937
  // OpenCL C 2.0 v2.2-11 s6.9.i:
938
  //     Recursion is not supported.
939
  //
940
  // SYCL v1.2.1 s3.10:
941
  //     kernels cannot include RTTI information, exception classes,
942
  //     recursive code, virtual functions or make use of C++ libraries that
943
  //     are not compiled for the device.
944
377k
  if (FD && 
(333k
(333k
getLangOpts().CPlusPlus333k
&&
FD->isMain()188k
) ||
945
333k
             
getLangOpts().OpenCL329k
||
getLangOpts().SYCLIsDevice327k
||
946
333k
             
(327k
getLangOpts().CUDA327k
&&
FD->hasAttr<CUDAGlobalAttr>()1.00k
)))
947
6.14k
    Fn->addFnAttr(llvm::Attribute::NoRecurse);
948
949
377k
  llvm::RoundingMode RM = getLangOpts().getFPRoundingMode();
950
377k
  llvm::fp::ExceptionBehavior FPExceptionBehavior =
951
377k
      ToConstrainedExceptMD(getLangOpts().getFPExceptionMode());
952
377k
  Builder.setDefaultConstrainedRounding(RM);
953
377k
  Builder.setDefaultConstrainedExcept(FPExceptionBehavior);
954
377k
  if ((FD && 
(333k
FD->UsesFPIntrin()333k
||
FD->hasAttr<StrictFPAttr>()331k
)) ||
955
377k
      
(375k
!FD375k
&&
(44.0k
FPExceptionBehavior != llvm::fp::ebIgnore44.0k
||
956
44.0k
               
RM != llvm::RoundingMode::NearestTiesToEven44.0k
))) {
957
1.79k
    Builder.setIsFPConstrained(true);
958
1.79k
    Fn->addFnAttr(llvm::Attribute::StrictFP);
959
1.79k
  }
960
961
  // If a custom alignment is used, force realigning to this alignment on
962
  // any main function which certainly will need it.
963
377k
  if (FD && 
(333k
(333k
FD->isMain()333k
||
FD->isMSVCRTEntryPoint()327k
) &&
964
333k
             
CGM.getCodeGenOpts().StackAlignment5.54k
))
965
1
    Fn->addFnAttr("stackrealign");
966
967
377k
  llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
968
969
  // Create a marker to make it easy to insert allocas into the entryblock
970
  // later.  Don't create this with the builder, because we don't want it
971
  // folded.
972
377k
  llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
973
377k
  AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB);
974
975
377k
  ReturnBlock = getJumpDestInCurrentScope("return");
976
977
377k
  Builder.SetInsertPoint(EntryBB);
978
979
  // If we're checking the return value, allocate space for a pointer to a
980
  // precise source location of the checked return statement.
981
377k
  if (requiresReturnValueCheck()) {
982
19
    ReturnLocation = CreateDefaultAlignTempAlloca(Int8PtrTy, "return.sloc.ptr");
983
19
    InitTempAlloca(ReturnLocation, llvm::ConstantPointerNull::get(Int8PtrTy));
984
19
  }
985
986
  // Emit subprogram debug descriptor.
987
377k
  if (CGDebugInfo *DI = getDebugInfo()) {
988
    // Reconstruct the type from the argument list so that implicit parameters,
989
    // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
990
    // convention.
991
102k
    CallingConv CC = CallingConv::CC_C;
992
102k
    if (FD)
993
99.1k
      if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
994
99.1k
        CC = SrcFnTy->getCallConv();
995
102k
    SmallVector<QualType, 16> ArgTypes;
996
102k
    for (const VarDecl *VD : Args)
997
172k
      ArgTypes.push_back(VD->getType());
998
102k
    QualType FnType = getContext().getFunctionType(
999
102k
        RetTy, ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
1000
102k
    DI->emitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, CurFuncIsThunk);
1001
102k
  }
1002
1003
377k
  if (ShouldInstrumentFunction()) {
1004
15
    if (CGM.getCodeGenOpts().InstrumentFunctions)
1005
10
      CurFn->addFnAttr("instrument-function-entry", "__cyg_profile_func_enter");
1006
15
    if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
1007
4
      CurFn->addFnAttr("instrument-function-entry-inlined",
1008
4
                       "__cyg_profile_func_enter");
1009
15
    if (CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
1010
1
      CurFn->addFnAttr("instrument-function-entry-inlined",
1011
1
                       "__cyg_profile_func_enter_bare");
1012
15
  }
1013
1014
  // Since emitting the mcount call here impacts optimizations such as function
1015
  // inlining, we just add an attribute to insert a mcount call in backend.
1016
  // The attribute "counting-function" is set to mcount function name which is
1017
  // architecture dependent.
1018
377k
  if (CGM.getCodeGenOpts().InstrumentForProfiling) {
1019
    // Calls to fentry/mcount should not be generated if function has
1020
    // the no_instrument_function attribute.
1021
147
    if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) {
1022
117
      if (CGM.getCodeGenOpts().CallFEntry)
1023
4
        Fn->addFnAttr("fentry-call", "true");
1024
113
      else {
1025
113
        Fn->addFnAttr("instrument-function-entry-inlined",
1026
113
                      getTarget().getMCountName());
1027
113
      }
1028
117
      if (CGM.getCodeGenOpts().MNopMCount) {
1029
2
        if (!CGM.getCodeGenOpts().CallFEntry)
1030
1
          CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
1031
1
            << "-mnop-mcount" << "-mfentry";
1032
2
        Fn->addFnAttr("mnop-mcount");
1033
2
      }
1034
1035
117
      if (CGM.getCodeGenOpts().RecordMCount) {
1036
2
        if (!CGM.getCodeGenOpts().CallFEntry)
1037
1
          CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
1038
1
            << "-mrecord-mcount" << "-mfentry";
1039
2
        Fn->addFnAttr("mrecord-mcount");
1040
2
      }
1041
117
    }
1042
147
  }
1043
1044
377k
  if (CGM.getCodeGenOpts().PackedStack) {
1045
2
    if (getContext().getTargetInfo().getTriple().getArch() !=
1046
2
        llvm::Triple::systemz)
1047
1
      CGM.getDiags().Report(diag::err_opt_not_valid_on_target)
1048
1
        << "-mpacked-stack";
1049
2
    Fn->addFnAttr("packed-stack");
1050
2
  }
1051
1052
377k
  if (CGM.getCodeGenOpts().WarnStackSize != UINT_MAX &&
1053
377k
      
!CGM.getDiags().isIgnored(diag::warn_fe_backend_frame_larger_than, Loc)33
)
1054
28
    Fn->addFnAttr("warn-stack-size",
1055
28
                  std::to_string(CGM.getCodeGenOpts().WarnStackSize));
1056
1057
377k
  if (RetTy->isVoidType()) {
1058
    // Void type; nothing to return.
1059
183k
    ReturnValue = Address::invalid();
1060
1061
    // Count the implicit return.
1062
183k
    if (!endsWithReturn(D))
1063
160k
      ++NumReturnExprs;
1064
193k
  } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) {
1065
    // Indirect return; emit returned value directly into sret slot.
1066
    // This reduces code size, and affects correctness in C++.
1067
2.91k
    auto AI = CurFn->arg_begin();
1068
2.91k
    if (CurFnInfo->getReturnInfo().isSRetAfterThis())
1069
50
      ++AI;
1070
2.91k
    ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign());
1071
2.91k
    if (!CurFnInfo->getReturnInfo().getIndirectByVal()) {
1072
1.19k
      ReturnValuePointer =
1073
1.19k
          CreateDefaultAlignTempAlloca(Int8PtrTy, "result.ptr");
1074
1.19k
      Builder.CreateStore(Builder.CreatePointerBitCastOrAddrSpaceCast(
1075
1.19k
                              ReturnValue.getPointer(), Int8PtrTy),
1076
1.19k
                          ReturnValuePointer);
1077
1.19k
    }
1078
191k
  } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
1079
191k
             
!hasScalarEvaluationKind(CurFnInfo->getReturnType())5
) {
1080
    // Load the sret pointer from the argument struct and return into that.
1081
5
    unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
1082
5
    llvm::Function::arg_iterator EI = CurFn->arg_end();
1083
5
    --EI;
1084
5
    llvm::Value *Addr = Builder.CreateStructGEP(
1085
5
        EI->getType()->getPointerElementType(), &*EI, Idx);
1086
5
    llvm::Type *Ty =
1087
5
        cast<llvm::GetElementPtrInst>(Addr)->getResultElementType();
1088
5
    ReturnValuePointer = Address(Addr, getPointerAlign());
1089
5
    Addr = Builder.CreateAlignedLoad(Ty, Addr, getPointerAlign(), "agg.result");
1090
5
    ReturnValue = Address(Addr, CGM.getNaturalTypeAlignment(RetTy));
1091
191k
  } else {
1092
191k
    ReturnValue = CreateIRTemp(RetTy, "retval");
1093
1094
    // Tell the epilog emitter to autorelease the result.  We do this
1095
    // now so that various specialized functions can suppress it
1096
    // during their IR-generation.
1097
191k
    if (getLangOpts().ObjCAutoRefCount &&
1098
191k
        
!CurFnInfo->isReturnsRetained()422
&&
1099
191k
        
RetTy->isObjCRetainableType()387
)
1100
159
      AutoreleaseResult = true;
1101
191k
  }
1102
1103
377k
  EmitStartEHSpec(CurCodeDecl);
1104
1105
377k
  PrologueCleanupDepth = EHStack.stable_begin();
1106
1107
  // Emit OpenMP specific initialization of the device functions.
1108
377k
  if (getLangOpts().OpenMP && 
CurCodeDecl70.4k
)
1109
64.0k
    CGM.getOpenMPRuntime().emitFunctionProlog(*this, CurCodeDecl);
1110
1111
377k
  EmitFunctionProlog(*CurFnInfo, CurFn, Args);
1112
1113
377k
  if (D && 
isa<CXXMethodDecl>(D)368k
&&
cast<CXXMethodDecl>(D)->isInstance()111k
) {
1114
104k
    CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
1115
104k
    const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
1116
104k
    if (MD->getParent()->isLambda() &&
1117
104k
        
MD->getOverloadedOperator() == OO_Call1.81k
) {
1118
      // We're in a lambda; figure out the captures.
1119
1.64k
      MD->getParent()->getCaptureFields(LambdaCaptureFields,
1120
1.64k
                                        LambdaThisCaptureField);
1121
1.64k
      if (LambdaThisCaptureField) {
1122
        // If the lambda captures the object referred to by '*this' - either by
1123
        // value or by reference, make sure CXXThisValue points to the correct
1124
        // object.
1125
1126
        // Get the lvalue for the field (which is a copy of the enclosing object
1127
        // or contains the address of the enclosing object).
1128
84
        LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
1129
84
        if (!LambdaThisCaptureField->getType()->isPointerType()) {
1130
          // If the enclosing object was captured by value, just use its address.
1131
2
          CXXThisValue = ThisFieldLValue.getAddress(*this).getPointer();
1132
82
        } else {
1133
          // Load the lvalue pointed to by the field, since '*this' was captured
1134
          // by reference.
1135
82
          CXXThisValue =
1136
82
              EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
1137
82
        }
1138
84
      }
1139
2.71k
      for (auto *FD : MD->getParent()->fields()) {
1140
2.71k
        if (FD->hasCapturedVLAType()) {
1141
24
          auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
1142
24
                                           SourceLocation()).getScalarVal();
1143
24
          auto VAT = FD->getCapturedVLAType();
1144
24
          VLASizeMap[VAT->getSizeExpr()] = ExprArg;
1145
24
        }
1146
2.71k
      }
1147
103k
    } else {
1148
      // Not in a lambda; just use 'this' from the method.
1149
      // FIXME: Should we generate a new load for each use of 'this'?  The
1150
      // fast register allocator would be happier...
1151
103k
      CXXThisValue = CXXABIThisValue;
1152
103k
    }
1153
1154
    // Check the 'this' pointer once per function, if it's available.
1155
104k
    if (CXXABIThisValue) {
1156
104k
      SanitizerSet SkippedChecks;
1157
104k
      SkippedChecks.set(SanitizerKind::ObjectSize, true);
1158
104k
      QualType ThisTy = MD->getThisType();
1159
1160
      // If this is the call operator of a lambda with no capture-default, it
1161
      // may have a static invoker function, which may call this operator with
1162
      // a null 'this' pointer.
1163
104k
      if (isLambdaCallOperator(MD) &&
1164
104k
          
MD->getParent()->getLambdaCaptureDefault() == LCD_None1.64k
)
1165
363
        SkippedChecks.set(SanitizerKind::Null, true);
1166
1167
104k
      EmitTypeCheck(
1168
104k
          isa<CXXConstructorDecl>(MD) ? 
TCK_ConstructorCall40.7k
:
TCK_MemberCall64.0k
,
1169
104k
          Loc, CXXABIThisValue, ThisTy, CXXABIThisAlignment, SkippedChecks);
1170
104k
    }
1171
104k
  }
1172
1173
  // If any of the arguments have a variably modified type, make sure to
1174
  // emit the type size.
1175
377k
  for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
1176
1.20M
       i != e; 
++i829k
) {
1177
829k
    const VarDecl *VD = *i;
1178
1179
    // Dig out the type as written from ParmVarDecls; it's unclear whether
1180
    // the standard (C99 6.9.1p10) requires this, but we're following the
1181
    // precedent set by gcc.
1182
829k
    QualType Ty;
1183
829k
    if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
1184
635k
      Ty = PVD->getOriginalType();
1185
193k
    else
1186
193k
      Ty = VD->getType();
1187
1188
829k
    if (Ty->isVariablyModifiedType())
1189
137
      EmitVariablyModifiedType(Ty);
1190
829k
  }
1191
  // Emit a location at the end of the prologue.
1192
377k
  if (CGDebugInfo *DI = getDebugInfo())
1193
102k
    DI->EmitLocation(Builder, StartLoc);
1194
1195
  // TODO: Do we need to handle this in two places like we do with
1196
  // target-features/target-cpu?
1197
377k
  if (CurFuncDecl)
1198
361k
    if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>())
1199
8.32k
      LargestVectorWidth = VecWidth->getVectorWidth();
1200
377k
}
1201
1202
274k
void CodeGenFunction::EmitFunctionBody(const Stmt *Body) {
1203
274k
  incrementProfileCounter(Body);
1204
274k
  if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
1205
274k
    EmitCompoundStmtWithoutScope(*S);
1206
59
  else
1207
59
    EmitStmt(Body);
1208
1209
  // This is checked after emitting the function body so we know if there
1210
  // are any permitted infinite loops.
1211
274k
  if (checkIfFunctionMustProgress())
1212
128k
    CurFn->addFnAttr(llvm::Attribute::MustProgress);
1213
274k
}
1214
1215
/// When instrumenting to collect profile data, the counts for some blocks
1216
/// such as switch cases need to not include the fall-through counts, so
1217
/// emit a branch around the instrumentation code. When not instrumenting,
1218
/// this just calls EmitBlock().
1219
void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
1220
1.91k
                                               const Stmt *S) {
1221
1.91k
  llvm::BasicBlock *SkipCountBB = nullptr;
1222
1.91k
  if (HaveInsertPoint() && 
CGM.getCodeGenOpts().hasProfileClangInstr()812
) {
1223
    // When instrumenting for profiling, the fallthrough to certain
1224
    // statements needs to skip over the instrumentation code so that we
1225
    // get an accurate count.
1226
23
    SkipCountBB = createBasicBlock("skipcount");
1227
23
    EmitBranch(SkipCountBB);
1228
23
  }
1229
1.91k
  EmitBlock(BB);
1230
1.91k
  uint64_t CurrentCount = getCurrentProfileCount();
1231
1.91k
  incrementProfileCounter(S);
1232
1.91k
  setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
1233
1.91k
  if (SkipCountBB)
1234
23
    EmitBlock(SkipCountBB);
1235
1.91k
}
1236
1237
/// Tries to mark the given function nounwind based on the
1238
/// non-existence of any throwing calls within it.  We believe this is
1239
/// lightweight enough to do at -O0.
1240
263k
static void TryMarkNoThrow(llvm::Function *F) {
1241
  // LLVM treats 'nounwind' on a function as part of the type, so we
1242
  // can't do this on functions that can be overwritten.
1243
263k
  if (F->isInterposable()) 
return41
;
1244
1245
263k
  for (llvm::BasicBlock &BB : *F)
1246
379k
    for (llvm::Instruction &I : BB)
1247
4.07M
      if (I.mayThrow())
1248
73.5k
        return;
1249
1250
189k
  F->setDoesNotThrow();
1251
189k
}
1252
1253
QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
1254
333k
                                               FunctionArgList &Args) {
1255
333k
  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1256
333k
  QualType ResTy = FD->getReturnType();
1257
1258
333k
  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1259
333k
  if (MD && 
MD->isInstance()111k
) {
1260
104k
    if (CGM.getCXXABI().HasThisReturn(GD))
1261
1.66k
      ResTy = MD->getThisType();
1262
103k
    else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
1263
214
      ResTy = CGM.getContext().VoidPtrTy;
1264
104k
    CGM.getCXXABI().buildThisParam(*this, Args);
1265
104k
  }
1266
1267
  // The base version of an inheriting constructor whose constructed base is a
1268
  // virtual base is not passed any arguments (because it doesn't actually call
1269
  // the inherited constructor).
1270
333k
  bool PassedParams = true;
1271
333k
  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
1272
40.8k
    if (auto Inherited = CD->getInheritedConstructor())
1273
225
      PassedParams =
1274
225
          getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
1275
1276
333k
  if (PassedParams) {
1277
633k
    for (auto *Param : FD->parameters()) {
1278
633k
      Args.push_back(Param);
1279
633k
      if (!Param->hasAttr<PassObjectSizeAttr>())
1280
633k
        continue;
1281
1282
88
      auto *Implicit = ImplicitParamDecl::Create(
1283
88
          getContext(), Param->getDeclContext(), Param->getLocation(),
1284
88
          /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamDecl::Other);
1285
88
      SizeArguments[Param] = Implicit;
1286
88
      Args.push_back(Implicit);
1287
88
    }
1288
333k
  }
1289
1290
333k
  if (MD && 
(111k
isa<CXXConstructorDecl>(MD)111k
||
isa<CXXDestructorDecl>(MD)70.3k
))
1291
57.6k
    CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
1292
1293
333k
  return ResTy;
1294
333k
}
1295
1296
void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1297
333k
                                   const CGFunctionInfo &FnInfo) {
1298
333k
  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1299
333k
  CurGD = GD;
1300
1301
333k
  FunctionArgList Args;
1302
333k
  QualType ResTy = BuildFunctionArgList(GD, Args);
1303
1304
  // Check if we should generate debug info for this function.
1305
333k
  if (FD->hasAttr<NoDebugAttr>()) {
1306
    // Clear non-distinct debug info that was possibly attached to the function
1307
    // due to an earlier declaration without the nodebug attribute
1308
13.9k
    if (Fn)
1309
13.9k
      Fn->setSubprogram(nullptr);
1310
    // Disable debug info indefinitely for this function
1311
13.9k
    DebugInfo = nullptr;
1312
13.9k
  }
1313
1314
  // The function might not have a body if we're generating thunks for a
1315
  // function declaration.
1316
333k
  SourceRange BodyRange;
1317
333k
  if (Stmt *Body = FD->getBody())
1318
332k
    BodyRange = Body->getSourceRange();
1319
128
  else
1320
128
    BodyRange = FD->getLocation();
1321
333k
  CurEHLocation = BodyRange.getEnd();
1322
1323
  // Use the location of the start of the function to determine where
1324
  // the function definition is located. By default use the location
1325
  // of the declaration as the location for the subprogram. A function
1326
  // may lack a declaration in the source code if it is created by code
1327
  // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
1328
333k
  SourceLocation Loc = FD->getLocation();
1329
1330
  // If this is a function specialization then use the pattern body
1331
  // as the location for the function.
1332
333k
  if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
1333
97.5k
    if (SpecDecl->hasBody(SpecDecl))
1334
96.7k
      Loc = SpecDecl->getLocation();
1335
1336
333k
  Stmt *Body = FD->getBody();
1337
1338
333k
  if (Body) {
1339
    // Coroutines always emit lifetime markers.
1340
332k
    if (isa<CoroutineBodyStmt>(Body))
1341
55
      ShouldEmitLifetimeMarkers = true;
1342
1343
    // Initialize helper which will detect jumps which can cause invalid
1344
    // lifetime markers.
1345
332k
    if (ShouldEmitLifetimeMarkers)
1346
46.2k
      Bypasses.Init(Body);
1347
332k
  }
1348
1349
  // Emit the standard function prologue.
1350
333k
  StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
1351
1352
  // Save parameters for coroutine function.
1353
333k
  if (Body && 
isa_and_nonnull<CoroutineBodyStmt>(Body)332k
)
1354
55
    for (const auto *ParamDecl : FD->parameters())
1355
32
      FnArgs.push_back(ParamDecl);
1356
1357
  // Generate the body of the function.
1358
333k
  PGO.assignRegionCounters(GD, CurFn);
1359
333k
  if (isa<CXXDestructorDecl>(FD))
1360
16.7k
    EmitDestructorBody(Args);
1361
316k
  else if (isa<CXXConstructorDecl>(FD))
1362
40.7k
    EmitConstructorBody(Args);
1363
275k
  else if (getLangOpts().CUDA &&
1364
275k
           
!getLangOpts().CUDAIsDevice823
&&
1365
275k
           
FD->hasAttr<CUDAGlobalAttr>()214
)
1366
63
    CGM.getCUDARuntime().emitDeviceStub(*this, Args);
1367
275k
  else if (isa<CXXMethodDecl>(FD) &&
1368
275k
           
cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()53.5k
) {
1369
    // The lambda static invoker function is special, because it forwards or
1370
    // clones the body of the function call operator (but is actually static).
1371
60
    EmitLambdaStaticInvokeBody(cast<CXXMethodDecl>(FD));
1372
275k
  } else if (FD->isDefaulted() && 
isa<CXXMethodDecl>(FD)746
&&
1373
275k
             
(742
cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator()742
||
1374
742
              
cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator()211
)) {
1375
    // Implicit copy-assignment gets the same special treatment as implicit
1376
    // copy-constructors.
1377
726
    emitImplicitAssignmentOperatorBody(Args);
1378
274k
  } else if (Body) {
1379
274k
    EmitFunctionBody(Body);
1380
274k
  } else
1381
0
    llvm_unreachable("no definition for emitted function");
1382
1383
  // C++11 [stmt.return]p2:
1384
  //   Flowing off the end of a function [...] results in undefined behavior in
1385
  //   a value-returning function.
1386
  // C11 6.9.1p12:
1387
  //   If the '}' that terminates a function is reached, and the value of the
1388
  //   function call is used by the caller, the behavior is undefined.
1389
333k
  if (getLangOpts().CPlusPlus && 
!FD->hasImplicitReturnZero()188k
&&
!SawAsmBlock184k
&&
1390
333k
      
!FD->getReturnType()->isVoidType()184k
&&
Builder.GetInsertBlock()77.8k
) {
1391
182
    bool ShouldEmitUnreachable =
1392
182
        CGM.getCodeGenOpts().StrictReturn ||
1393
182
        
!CGM.MayDropFunctionReturn(FD->getASTContext(), FD->getReturnType())21
;
1394
182
    if (SanOpts.has(SanitizerKind::Return)) {
1395
1
      SanitizerScope SanScope(this);
1396
1
      llvm::Value *IsFalse = Builder.getFalse();
1397
1
      EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
1398
1
                SanitizerHandler::MissingReturn,
1399
1
                EmitCheckSourceLocation(FD->getLocation()), None);
1400
181
    } else if (ShouldEmitUnreachable) {
1401
163
      if (CGM.getCodeGenOpts().OptimizationLevel == 0)
1402
132
        EmitTrapCall(llvm::Intrinsic::trap);
1403
163
    }
1404
182
    if (SanOpts.has(SanitizerKind::Return) || 
ShouldEmitUnreachable181
) {
1405
164
      Builder.CreateUnreachable();
1406
164
      Builder.ClearInsertionPoint();
1407
164
    }
1408
182
  }
1409
1410
  // Emit the standard function epilogue.
1411
333k
  FinishFunction(BodyRange.getEnd());
1412
1413
  // If we haven't marked the function nothrow through other means, do
1414
  // a quick pass now to see if we can.
1415
333k
  if (!CurFn->doesNotThrow())
1416
263k
    TryMarkNoThrow(CurFn);
1417
333k
}
1418
1419
/// ContainsLabel - Return true if the statement contains a label in it.  If
1420
/// this statement is not executed normally, it not containing a label means
1421
/// that we can just remove the code.
1422
66.5k
bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
1423
  // Null statement, not a label!
1424
66.5k
  if (!S) 
return false102
;
1425
1426
  // If this is a label, we have to emit the code, consider something like:
1427
  // if (0) {  ...  foo:  bar(); }  goto foo;
1428
  //
1429
  // TODO: If anyone cared, we could track __label__'s, since we know that you
1430
  // can't jump to one from outside their declared region.
1431
66.4k
  if (isa<LabelStmt>(S))
1432
6
    return true;
1433
1434
  // If this is a case/default statement, and we haven't seen a switch, we have
1435
  // to emit the code.
1436
66.4k
  if (isa<SwitchCase>(S) && 
!IgnoreCaseStmts68
)
1437
0
    return true;
1438
1439
  // If this is a switch statement, we want to ignore cases below it.
1440
66.4k
  if (isa<SwitchStmt>(S))
1441
10
    IgnoreCaseStmts = true;
1442
1443
  // Scan subexpressions for verboten labels.
1444
66.4k
  for (const Stmt *SubStmt : S->children())
1445
49.6k
    if (ContainsLabel(SubStmt, IgnoreCaseStmts))
1446
13
      return true;
1447
1448
66.4k
  return false;
1449
66.4k
}
1450
1451
/// containsBreak - Return true if the statement contains a break out of it.
1452
/// If the statement (recursively) contains a switch or loop with a break
1453
/// inside of it, this is fine.
1454
952
bool CodeGenFunction::containsBreak(const Stmt *S) {
1455
  // Null statement, not a label!
1456
952
  if (!S) 
return false0
;
1457
1458
  // If this is a switch or loop that defines its own break scope, then we can
1459
  // include it and anything inside of it.
1460
952
  if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
1461
952
      
isa<ForStmt>(S)949
)
1462
3
    return false;
1463
1464
949
  if (isa<BreakStmt>(S))
1465
1
    return true;
1466
1467
  // Scan subexpressions for verboten breaks.
1468
948
  for (const Stmt *SubStmt : S->children())
1469
870
    if (containsBreak(SubStmt))
1470
1
      return true;
1471
1472
947
  return false;
1473
948
}
1474
1475
2.61k
bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) {
1476
2.61k
  if (!S) 
return false0
;
1477
1478
  // Some statement kinds add a scope and thus never add a decl to the current
1479
  // scope. Note, this list is longer than the list of statements that might
1480
  // have an unscoped decl nested within them, but this way is conservatively
1481
  // correct even if more statement kinds are added.
1482
2.61k
  if (isa<IfStmt>(S) || 
isa<SwitchStmt>(S)2.61k
||
isa<WhileStmt>(S)2.61k
||
1483
2.61k
      
isa<DoStmt>(S)2.61k
||
isa<ForStmt>(S)2.61k
||
isa<CompoundStmt>(S)2.61k
||
1484
2.61k
      
isa<CXXForRangeStmt>(S)2.60k
||
isa<CXXTryStmt>(S)2.60k
||
1485
2.61k
      
isa<ObjCForCollectionStmt>(S)2.60k
||
isa<ObjCAtTryStmt>(S)2.60k
)
1486
15
    return false;
1487
1488
2.60k
  if (isa<DeclStmt>(S))
1489
7
    return true;
1490
1491
2.59k
  for (const Stmt *SubStmt : S->children())
1492
2.34k
    if (mightAddDeclToScope(SubStmt))
1493
2
      return true;
1494
1495
2.59k
  return false;
1496
2.59k
}
1497
1498
/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1499
/// to a constant, or if it does but contains a label, return false.  If it
1500
/// constant folds return true and set the boolean result in Result.
1501
bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1502
                                                   bool &ResultBool,
1503
161k
                                                   bool AllowLabels) {
1504
161k
  llvm::APSInt ResultInt;
1505
161k
  if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
1506
146k
    return false;
1507
1508
14.8k
  ResultBool = ResultInt.getBoolValue();
1509
14.8k
  return true;
1510
161k
}
1511
1512
/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1513
/// to a constant, or if it does but contains a label, return false.  If it
1514
/// constant folds return true and set the folded value.
1515
bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1516
                                                   llvm::APSInt &ResultInt,
1517
161k
                                                   bool AllowLabels) {
1518
  // FIXME: Rename and handle conversion of other evaluatable things
1519
  // to bool.
1520
161k
  Expr::EvalResult Result;
1521
161k
  if (!Cond->EvaluateAsInt(Result, getContext()))
1522
146k
    return false;  // Not foldable, not integer or not fully evaluatable.
1523
1524
14.9k
  llvm::APSInt Int = Result.Val.getInt();
1525
14.9k
  if (!AllowLabels && 
CodeGenFunction::ContainsLabel(Cond)14.9k
)
1526
0
    return false;  // Contains a label.
1527
1528
14.9k
  ResultInt = Int;
1529
14.9k
  return true;
1530
14.9k
}
1531
1532
/// Determine whether the given condition is an instrumentable condition
1533
/// (i.e. no "&&" or "||").
1534
672
bool CodeGenFunction::isInstrumentedCondition(const Expr *C) {
1535
  // Bypass simplistic logical-NOT operator before determining whether the
1536
  // condition contains any other logical operator.
1537
672
  if (const UnaryOperator *UnOp = dyn_cast<UnaryOperator>(C->IgnoreParens()))
1538
9
    if (UnOp->getOpcode() == UO_LNot)
1539
8
      C = UnOp->getSubExpr();
1540
1541
672
  const BinaryOperator *BOp = dyn_cast<BinaryOperator>(C->IgnoreParens());
1542
672
  return (!BOp || 
!BOp->isLogicalOp()256
);
1543
672
}
1544
1545
/// EmitBranchToCounterBlock - Emit a conditional branch to a new block that
1546
/// increments a profile counter based on the semantics of the given logical
1547
/// operator opcode.  This is used to instrument branch condition coverage for
1548
/// logical operators.
1549
void CodeGenFunction::EmitBranchToCounterBlock(
1550
    const Expr *Cond, BinaryOperator::Opcode LOp, llvm::BasicBlock *TrueBlock,
1551
    llvm::BasicBlock *FalseBlock, uint64_t TrueCount /* = 0 */,
1552
7.70k
    Stmt::Likelihood LH /* =None */, const Expr *CntrIdx /* = nullptr */) {
1553
  // If not instrumenting, just emit a branch.
1554
7.70k
  bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr();
1555
7.70k
  if (!InstrumentRegions || 
!isInstrumentedCondition(Cond)78
)
1556
7.64k
    return EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount, LH);
1557
1558
62
  llvm::BasicBlock *ThenBlock = NULL;
1559
62
  llvm::BasicBlock *ElseBlock = NULL;
1560
62
  llvm::BasicBlock *NextBlock = NULL;
1561
1562
  // Create the block we'll use to increment the appropriate counter.
1563
62
  llvm::BasicBlock *CounterIncrBlock = createBasicBlock("lop.rhscnt");
1564
1565
  // Set block pointers according to Logical-AND (BO_LAnd) semantics. This
1566
  // means we need to evaluate the condition and increment the counter on TRUE:
1567
  //
1568
  // if (Cond)
1569
  //   goto CounterIncrBlock;
1570
  // else
1571
  //   goto FalseBlock;
1572
  //
1573
  // CounterIncrBlock:
1574
  //   Counter++;
1575
  //   goto TrueBlock;
1576
1577
62
  if (LOp == BO_LAnd) {
1578
35
    ThenBlock = CounterIncrBlock;
1579
35
    ElseBlock = FalseBlock;
1580
35
    NextBlock = TrueBlock;
1581
35
  }
1582
1583
  // Set block pointers according to Logical-OR (BO_LOr) semantics. This means
1584
  // we need to evaluate the condition and increment the counter on FALSE:
1585
  //
1586
  // if (Cond)
1587
  //   goto TrueBlock;
1588
  // else
1589
  //   goto CounterIncrBlock;
1590
  //
1591
  // CounterIncrBlock:
1592
  //   Counter++;
1593
  //   goto FalseBlock;
1594
1595
27
  else if (LOp == BO_LOr) {
1596
27
    ThenBlock = TrueBlock;
1597
27
    ElseBlock = CounterIncrBlock;
1598
27
    NextBlock = FalseBlock;
1599
27
  } else {
1600
0
    llvm_unreachable("Expected Opcode must be that of a Logical Operator");
1601
0
  }
1602
1603
  // Emit Branch based on condition.
1604
62
  EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, TrueCount, LH);
1605
1606
  // Emit the block containing the counter increment(s).
1607
62
  EmitBlock(CounterIncrBlock);
1608
1609
  // Increment corresponding counter; if index not provided, use Cond as index.
1610
62
  incrementProfileCounter(CntrIdx ? 
CntrIdx2
:
Cond60
);
1611
1612
  // Go to the next block.
1613
62
  EmitBranch(NextBlock);
1614
62
}
1615
1616
/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1617
/// statement) to the specified blocks.  Based on the condition, this might try
1618
/// to simplify the codegen of the conditional based on the branch.
1619
/// \param LH The value of the likelihood attribute on the True branch.
1620
void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
1621
                                           llvm::BasicBlock *TrueBlock,
1622
                                           llvm::BasicBlock *FalseBlock,
1623
                                           uint64_t TrueCount,
1624
161k
                                           Stmt::Likelihood LH) {
1625
161k
  Cond = Cond->IgnoreParens();
1626
1627
161k
  if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
1628
1629
    // Handle X && Y in a condition.
1630
71.0k
    if (CondBOp->getOpcode() == BO_LAnd) {
1631
      // If we have "1 && X", simplify the code.  "0 && X" would have constant
1632
      // folded if the case was simple enough.
1633
7.18k
      bool ConstantBool = false;
1634
7.18k
      if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1635
7.18k
          
ConstantBool62
) {
1636
        // br(1 && X) -> br(X).
1637
62
        incrementProfileCounter(CondBOp);
1638
62
        return EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
1639
62
                                        FalseBlock, TrueCount, LH);
1640
62
      }
1641
1642
      // If we have "X && 1", simplify the code to use an uncond branch.
1643
      // "X && 0" would have been constant folded to 0.
1644
7.12k
      if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1645
7.12k
          
ConstantBool29
) {
1646
        // br(X && 1) -> br(X).
1647
29
        return EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LAnd, TrueBlock,
1648
29
                                        FalseBlock, TrueCount, LH, CondBOp);
1649
29
      }
1650
1651
      // Emit the LHS as a conditional.  If the LHS conditional is false, we
1652
      // want to jump to the FalseBlock.
1653
7.09k
      llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
1654
      // The counter tells us how often we evaluate RHS, and all of TrueCount
1655
      // can be propagated to that branch.
1656
7.09k
      uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
1657
1658
7.09k
      ConditionalEvaluation eval(*this);
1659
7.09k
      {
1660
7.09k
        ApplyDebugLocation DL(*this, Cond);
1661
        // Propagate the likelihood attribute like __builtin_expect
1662
        // __builtin_expect(X && Y, 1) -> X and Y are likely
1663
        // __builtin_expect(X && Y, 0) -> only Y is unlikely
1664
7.09k
        EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount,
1665
7.09k
                             LH == Stmt::LH_Unlikely ? 
Stmt::LH_None1
:
LH7.09k
);
1666
7.09k
        EmitBlock(LHSTrue);
1667
7.09k
      }
1668
1669
7.09k
      incrementProfileCounter(CondBOp);
1670
7.09k
      setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1671
1672
      // Any temporaries created here are conditional.
1673
7.09k
      eval.begin(*this);
1674
7.09k
      EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
1675
7.09k
                               FalseBlock, TrueCount, LH);
1676
7.09k
      eval.end(*this);
1677
1678
7.09k
      return;
1679
7.12k
    }
1680
1681
63.8k
    if (CondBOp->getOpcode() == BO_LOr) {
1682
      // If we have "0 || X", simplify the code.  "1 || X" would have constant
1683
      // folded if the case was simple enough.
1684
516
      bool ConstantBool = false;
1685
516
      if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1686
516
          
!ConstantBool7
) {
1687
        // br(0 || X) -> br(X).
1688
7
        incrementProfileCounter(CondBOp);
1689
7
        return EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock,
1690
7
                                        FalseBlock, TrueCount, LH);
1691
7
      }
1692
1693
      // If we have "X || 0", simplify the code to use an uncond branch.
1694
      // "X || 1" would have been constant folded to 1.
1695
509
      if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1696
509
          
!ConstantBool1
) {
1697
        // br(X || 0) -> br(X).
1698
1
        return EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LOr, TrueBlock,
1699
1
                                        FalseBlock, TrueCount, LH, CondBOp);
1700
1
      }
1701
1702
      // Emit the LHS as a conditional.  If the LHS conditional is true, we
1703
      // want to jump to the TrueBlock.
1704
508
      llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
1705
      // We have the count for entry to the RHS and for the whole expression
1706
      // being true, so we can divy up True count between the short circuit and
1707
      // the RHS.
1708
508
      uint64_t LHSCount =
1709
508
          getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
1710
508
      uint64_t RHSCount = TrueCount - LHSCount;
1711
1712
508
      ConditionalEvaluation eval(*this);
1713
508
      {
1714
        // Propagate the likelihood attribute like __builtin_expect
1715
        // __builtin_expect(X || Y, 1) -> only Y is likely
1716
        // __builtin_expect(X || Y, 0) -> both X and Y are unlikely
1717
508
        ApplyDebugLocation DL(*this, Cond);
1718
508
        EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount,
1719
508
                             LH == Stmt::LH_Likely ? 
Stmt::LH_None1
:
LH507
);
1720
508
        EmitBlock(LHSFalse);
1721
508
      }
1722
1723
508
      incrementProfileCounter(CondBOp);
1724
508
      setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1725
1726
      // Any temporaries created here are conditional.
1727
508
      eval.begin(*this);
1728
508
      EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock, FalseBlock,
1729
508
                               RHSCount, LH);
1730
1731
508
      eval.end(*this);
1732
1733
508
      return;
1734
509
    }
1735
63.8k
  }
1736
1737
153k
  if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1738
    // br(!x, t, f) -> br(x, f, t)
1739
1.36k
    if (CondUOp->getOpcode() == UO_LNot) {
1740
      // Negate the count.
1741
1.36k
      uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
1742
      // The values of the enum are chosen to make this negation possible.
1743
1.36k
      LH = static_cast<Stmt::Likelihood>(-LH);
1744
      // Negate the condition and swap the destination blocks.
1745
1.36k
      return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
1746
1.36k
                                  FalseCount, LH);
1747
1.36k
    }
1748
1.36k
  }
1749
1750
152k
  if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
1751
    // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
1752
2
    llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
1753
2
    llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
1754
1755
    // The ConditionalOperator itself has no likelihood information for its
1756
    // true and false branches. This matches the behavior of __builtin_expect.
1757
2
    ConditionalEvaluation cond(*this);
1758
2
    EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
1759
2
                         getProfileCount(CondOp), Stmt::LH_None);
1760
1761
    // When computing PGO branch weights, we only know the overall count for
1762
    // the true block. This code is essentially doing tail duplication of the
1763
    // naive code-gen, introducing new edges for which counts are not
1764
    // available. Divide the counts proportionally between the LHS and RHS of
1765
    // the conditional operator.
1766
2
    uint64_t LHSScaledTrueCount = 0;
1767
2
    if (TrueCount) {
1768
0
      double LHSRatio =
1769
0
          getProfileCount(CondOp) / (double)getCurrentProfileCount();
1770
0
      LHSScaledTrueCount = TrueCount * LHSRatio;
1771
0
    }
1772
1773
2
    cond.begin(*this);
1774
2
    EmitBlock(LHSBlock);
1775
2
    incrementProfileCounter(CondOp);
1776
2
    {
1777
2
      ApplyDebugLocation DL(*this, Cond);
1778
2
      EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
1779
2
                           LHSScaledTrueCount, LH);
1780
2
    }
1781
2
    cond.end(*this);
1782
1783
2
    cond.begin(*this);
1784
2
    EmitBlock(RHSBlock);
1785
2
    EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
1786
2
                         TrueCount - LHSScaledTrueCount, LH);
1787
2
    cond.end(*this);
1788
1789
2
    return;
1790
2
  }
1791
1792
152k
  if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
1793
    // Conditional operator handling can give us a throw expression as a
1794
    // condition for a case like:
1795
    //   br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
1796
    // Fold this to:
1797
    //   br(c, throw x, br(y, t, f))
1798
0
    EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
1799
0
    return;
1800
0
  }
1801
1802
  // Emit the code with the fully general case.
1803
152k
  llvm::Value *CondV;
1804
152k
  {
1805
152k
    ApplyDebugLocation DL(*this, Cond);
1806
152k
    CondV = EvaluateExprAsBool(Cond);
1807
152k
  }
1808
1809
152k
  llvm::MDNode *Weights = nullptr;
1810
152k
  llvm::MDNode *Unpredictable = nullptr;
1811
1812
  // If the branch has a condition wrapped by __builtin_unpredictable,
1813
  // create metadata that specifies that the branch is unpredictable.
1814
  // Don't bother if not optimizing because that metadata would not be used.
1815
152k
  auto *Call = dyn_cast<CallExpr>(Cond->IgnoreImpCasts());
1816
152k
  if (Call && 
CGM.getCodeGenOpts().OptimizationLevel != 05.95k
) {
1817
101
    auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
1818
101
    if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
1819
2
      llvm::MDBuilder MDHelper(getLLVMContext());
1820
2
      Unpredictable = MDHelper.createUnpredictable();
1821
2
    }
1822
101
  }
1823
1824
  // If there is a Likelihood knowledge for the cond, lower it.
1825
  // Note that if not optimizing this won't emit anything.
1826
152k
  llvm::Value *NewCondV = emitCondLikelihoodViaExpectIntrinsic(CondV, LH);
1827
152k
  if (CondV != NewCondV)
1828
40
    CondV = NewCondV;
1829
152k
  else {
1830
    // Otherwise, lower profile counts. Note that we do this even at -O0.
1831
152k
    uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
1832
152k
    Weights = createProfileWeights(TrueCount, CurrentCount - TrueCount);
1833
152k
  }
1834
1835
152k
  Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
1836
152k
}
1837
1838
/// ErrorUnsupported - Print out an error that codegen doesn't support the
1839
/// specified stmt yet.
1840
1
void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
1841
1
  CGM.ErrorUnsupported(S, Type);
1842
1
}
1843
1844
/// emitNonZeroVLAInit - Emit the "zero" initialization of a
1845
/// variable-length array whose elements have a non-zero bit-pattern.
1846
///
1847
/// \param baseType the inner-most element type of the array
1848
/// \param src - a char* pointing to the bit-pattern for a single
1849
/// base element of the array
1850
/// \param sizeInChars - the total size of the VLA, in chars
1851
static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
1852
                               Address dest, Address src,
1853
0
                               llvm::Value *sizeInChars) {
1854
0
  CGBuilderTy &Builder = CGF.Builder;
1855
1856
0
  CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
1857
0
  llvm::Value *baseSizeInChars
1858
0
    = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
1859
1860
0
  Address begin =
1861
0
    Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin");
1862
0
  llvm::Value *end = Builder.CreateInBoundsGEP(
1863
0
      begin.getElementType(), begin.getPointer(), sizeInChars, "vla.end");
1864
1865
0
  llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
1866
0
  llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
1867
0
  llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
1868
1869
  // Make a loop over the VLA.  C99 guarantees that the VLA element
1870
  // count must be nonzero.
1871
0
  CGF.EmitBlock(loopBB);
1872
1873
0
  llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
1874
0
  cur->addIncoming(begin.getPointer(), originBB);
1875
1876
0
  CharUnits curAlign =
1877
0
    dest.getAlignment().alignmentOfArrayElement(baseSize);
1878
1879
  // memcpy the individual element bit-pattern.
1880
0
  Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars,
1881
0
                       /*volatile*/ false);
1882
1883
  // Go to the next element.
1884
0
  llvm::Value *next =
1885
0
    Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
1886
1887
  // Leave if that's the end of the VLA.
1888
0
  llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
1889
0
  Builder.CreateCondBr(done, contBB, loopBB);
1890
0
  cur->addIncoming(next, loopBB);
1891
1892
0
  CGF.EmitBlock(contBB);
1893
0
}
1894
1895
void
1896
7.07k
CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
1897
  // Ignore empty classes in C++.
1898
7.07k
  if (getLangOpts().CPlusPlus) {
1899
6.93k
    if (const RecordType *RT = Ty->getAs<RecordType>()) {
1900
6.58k
      if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
1901
5.86k
        return;
1902
6.58k
    }
1903
6.93k
  }
1904
1905
  // Cast the dest ptr to the appropriate i8 pointer type.
1906
1.21k
  if (DestPtr.getElementType() != Int8Ty)
1907
1.21k
    DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
1908
1909
  // Get size and alignment info for this aggregate.
1910
1.21k
  CharUnits size = getContext().getTypeSizeInChars(Ty);
1911
1912
1.21k
  llvm::Value *SizeVal;
1913
1.21k
  const VariableArrayType *vla;
1914
1915
  // Don't bother emitting a zero-byte memset.
1916
1.21k
  if (size.isZero()) {
1917
    // But note that getTypeInfo returns 0 for a VLA.
1918
11
    if (const VariableArrayType *vlaType =
1919
11
          dyn_cast_or_null<VariableArrayType>(
1920
11
                                          getContext().getAsArrayType(Ty))) {
1921
8
      auto VlaSize = getVLASize(vlaType);
1922
8
      SizeVal = VlaSize.NumElts;
1923
8
      CharUnits eltSize = getContext().getTypeSizeInChars(VlaSize.Type);
1924
8
      if (!eltSize.isOne())
1925
8
        SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
1926
8
      vla = vlaType;
1927
8
    } else {
1928
3
      return;
1929
3
    }
1930
1.20k
  } else {
1931
1.20k
    SizeVal = CGM.getSize(size);
1932
1.20k
    vla = nullptr;
1933
1.20k
  }
1934
1935
  // If the type contains a pointer to data member we can't memset it to zero.
1936
  // Instead, create a null constant and copy it to the destination.
1937
  // TODO: there are other patterns besides zero that we can usefully memset,
1938
  // like -1, which happens to be the pattern used by member-pointers.
1939
1.21k
  if (!CGM.getTypes().isZeroInitializable(Ty)) {
1940
    // For a VLA, emit a single element, then splat that over the VLA.
1941
9
    if (vla) 
Ty = getContext().getBaseElementType(vla)0
;
1942
1943
9
    llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
1944
1945
9
    llvm::GlobalVariable *NullVariable =
1946
9
      new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
1947
9
                               /*isConstant=*/true,
1948
9
                               llvm::GlobalVariable::PrivateLinkage,
1949
9
                               NullConstant, Twine());
1950
9
    CharUnits NullAlign = DestPtr.getAlignment();
1951
9
    NullVariable->setAlignment(NullAlign.getAsAlign());
1952
9
    Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()),
1953
9
                   NullAlign);
1954
1955
9
    if (vla) 
return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal)0
;
1956
1957
    // Get and call the appropriate llvm.memcpy overload.
1958
9
    Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
1959
9
    return;
1960
9
  }
1961
1962
  // Otherwise, just memset the whole thing to zero.  This is legal
1963
  // because in LLVM, all default initializers (other than the ones we just
1964
  // handled above) are guaranteed to have a bit pattern of all zeros.
1965
1.20k
  Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
1966
1.20k
}
1967
1968
57
llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
1969
  // Make sure that there is a block for the indirect goto.
1970
57
  if (!IndirectBranch)
1971
34
    GetIndirectGotoBlock();
1972
1973
57
  llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
1974
1975
  // Make sure the indirect branch includes all of the address-taken blocks.
1976
57
  IndirectBranch->addDestination(BB);
1977
57
  return llvm::BlockAddress::get(CurFn, BB);
1978
57
}
1979
1980
56
llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
1981
  // If we already made the indirect branch for indirect goto, return its block.
1982
56
  if (IndirectBranch) 
return IndirectBranch->getParent()21
;
1983
1984
35
  CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
1985
1986
  // Create the PHI node that indirect gotos will add entries to.
1987
35
  llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
1988
35
                                              "indirect.goto.dest");
1989
1990
  // Create the indirect branch instruction.
1991
35
  IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
1992
35
  return IndirectBranch->getParent();
1993
56
}
1994
1995
/// Computes the length of an array in elements, as well as the base
1996
/// element type and a properly-typed first element pointer.
1997
llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
1998
                                              QualType &baseType,
1999
4.79k
                                              Address &addr) {
2000
4.79k
  const ArrayType *arrayType = origArrayType;
2001
2002
  // If it's a VLA, we have to load the stored size.  Note that
2003
  // this is the size of the VLA in bytes, not its size in elements.
2004
4.79k
  llvm::Value *numVLAElements = nullptr;
2005
4.79k
  if (isa<VariableArrayType>(arrayType)) {
2006
614
    numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).NumElts;
2007
2008
    // Walk into all VLAs.  This doesn't require changes to addr,
2009
    // which has type T* where T is the first non-VLA element type.
2010
651
    do {
2011
651
      QualType elementType = arrayType->getElementType();
2012
651
      arrayType = getContext().getAsArrayType(elementType);
2013
2014
      // If we only have VLA components, 'addr' requires no adjustment.
2015
651
      if (!arrayType) {
2016
610
        baseType = elementType;
2017
610
        return numVLAElements;
2018
610
      }
2019
651
    } while (
isa<VariableArrayType>(arrayType)41
);
2020
2021
    // We get out here only if we find a constant array type
2022
    // inside the VLA.
2023
614
  }
2024
2025
  // We have some number of constant-length arrays, so addr should
2026
  // have LLVM type [M x [N x [...]]]*.  Build a GEP that walks
2027
  // down to the first element of addr.
2028
4.18k
  SmallVector<llvm::Value*, 8> gepIndices;
2029
2030
  // GEP down to the array type.
2031
4.18k
  llvm::ConstantInt *zero = Builder.getInt32(0);
2032
4.18k
  gepIndices.push_back(zero);
2033
2034
4.18k
  uint64_t countFromCLAs = 1;
2035
4.18k
  QualType eltType;
2036
2037
4.18k
  llvm::ArrayType *llvmArrayType =
2038
4.18k
    dyn_cast<llvm::ArrayType>(addr.getElementType());
2039
8.14k
  while (llvmArrayType) {
2040
3.95k
    assert(isa<ConstantArrayType>(arrayType));
2041
0
    assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
2042
3.95k
             == llvmArrayType->getNumElements());
2043
2044
0
    gepIndices.push_back(zero);
2045
3.95k
    countFromCLAs *= llvmArrayType->getNumElements();
2046
3.95k
    eltType = arrayType->getElementType();
2047
2048
3.95k
    llvmArrayType =
2049
3.95k
      dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
2050
3.95k
    arrayType = getContext().getAsArrayType(arrayType->getElementType());
2051
3.95k
    assert((!llvmArrayType || arrayType) &&
2052
3.95k
           "LLVM and Clang types are out-of-synch");
2053
3.95k
  }
2054
2055
4.18k
  if (arrayType) {
2056
    // From this point onwards, the Clang array type has been emitted
2057
    // as some other type (probably a packed struct). Compute the array
2058
    // size, and just emit the 'begin' expression as a bitcast.
2059
694
    while (arrayType) {
2060
368
      countFromCLAs *=
2061
368
          cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
2062
368
      eltType = arrayType->getElementType();
2063
368
      arrayType = getContext().getAsArrayType(eltType);
2064
368
    }
2065
2066
326
    llvm::Type *baseType = ConvertType(eltType);
2067
326
    addr = Builder.CreateElementBitCast(addr, baseType, "array.begin");
2068
3.86k
  } else {
2069
    // Create the actual GEP.
2070
3.86k
    addr = Address(Builder.CreateInBoundsGEP(
2071
3.86k
        addr.getElementType(), addr.getPointer(), gepIndices, "array.begin"),
2072
3.86k
        addr.getAlignment());
2073
3.86k
  }
2074
2075
4.18k
  baseType = eltType;
2076
2077
4.18k
  llvm::Value *numElements
2078
4.18k
    = llvm::ConstantInt::get(SizeTy, countFromCLAs);
2079
2080
  // If we had any VLA dimensions, factor them in.
2081
4.18k
  if (numVLAElements)
2082
4
    numElements = Builder.CreateNUWMul(numVLAElements, numElements);
2083
2084
4.18k
  return numElements;
2085
4.79k
}
2086
2087
2.15k
CodeGenFunction::VlaSizePair CodeGenFunction::getVLASize(QualType type) {
2088
2.15k
  const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
2089
2.15k
  assert(vla && "type was not a variable array type!");
2090
0
  return getVLASize(vla);
2091
2.15k
}
2092
2093
CodeGenFunction::VlaSizePair
2094
5.75k
CodeGenFunction::getVLASize(const VariableArrayType *type) {
2095
  // The number of elements so far; always size_t.
2096
5.75k
  llvm::Value *numElements = nullptr;
2097
2098
5.75k
  QualType elementType;
2099
7.29k
  do {
2100
7.29k
    elementType = type->getElementType();
2101
7.29k
    llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
2102
7.29k
    assert(vlaSize && "no size for VLA!");
2103
0
    assert(vlaSize->getType() == SizeTy);
2104
2105
7.29k
    if (!numElements) {
2106
5.75k
      numElements = vlaSize;
2107
5.75k
    } else {
2108
      // It's undefined behavior if this wraps around, so mark it that way.
2109
      // FIXME: Teach -fsanitize=undefined to trap this.
2110
1.54k
      numElements = Builder.CreateNUWMul(numElements, vlaSize);
2111
1.54k
    }
2112
7.29k
  } while ((type = getContext().getAsVariableArrayType(elementType)));
2113
2114
0
  return { numElements, elementType };
2115
5.75k
}
2116
2117
CodeGenFunction::VlaSizePair
2118
3.19k
CodeGenFunction::getVLAElements1D(QualType type) {
2119
3.19k
  const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
2120
3.19k
  assert(vla && "type was not a variable array type!");
2121
0
  return getVLAElements1D(vla);
2122
3.19k
}
2123
2124
CodeGenFunction::VlaSizePair
2125
3.19k
CodeGenFunction::getVLAElements1D(const VariableArrayType *Vla) {
2126
3.19k
  llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()];
2127
3.19k
  assert(VlaSize && "no size for VLA!");
2128
0
  assert(VlaSize->getType() == SizeTy);
2129
0
  return { VlaSize, Vla->getElementType() };
2130
3.19k
}
2131
2132
2.85k
void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
2133
2.85k
  assert(type->isVariablyModifiedType() &&
2134
2.85k
         "Must pass variably modified type to EmitVLASizes!");
2135
2136
0
  EnsureInsertPoint();
2137
2138
  // We're going to walk down into the type and look for VLA
2139
  // expressions.
2140
4.05k
  do {
2141
4.05k
    assert(type->isVariablyModifiedType());
2142
2143
0
    const Type *ty = type.getTypePtr();
2144
4.05k
    switch (ty->getTypeClass()) {
2145
2146
0
#define TYPE(Class, Base)
2147
0
#define ABSTRACT_TYPE(Class, Base)
2148
0
#define NON_CANONICAL_TYPE(Class, Base)
2149
0
#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2150
0
#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
2151
0
#include "clang/AST/TypeNodes.inc"
2152
0
      llvm_unreachable("unexpected dependent type!");
2153
2154
    // These types are never variably-modified.
2155
0
    case Type::Builtin:
2156
0
    case Type::Complex:
2157
0
    case Type::Vector:
2158
0
    case Type::ExtVector:
2159
0
    case Type::ConstantMatrix:
2160
0
    case Type::Record:
2161
0
    case Type::Enum:
2162
0
    case Type::Elaborated:
2163
0
    case Type::TemplateSpecialization:
2164
0
    case Type::ObjCTypeParam:
2165
0
    case Type::ObjCObject:
2166
0
    case Type::ObjCInterface:
2167
0
    case Type::ObjCObjectPointer:
2168
0
    case Type::ExtInt:
2169
0
      llvm_unreachable("type class is never variably-modified!");
2170
2171
0
    case Type::Adjusted:
2172
0
      type = cast<AdjustedType>(ty)->getAdjustedType();
2173
0
      break;
2174
2175
70
    case Type::Decayed:
2176
70
      type = cast<DecayedType>(ty)->getPointeeType();
2177
70
      break;
2178
2179
90
    case Type::Pointer:
2180
90
      type = cast<PointerType>(ty)->getPointeeType();
2181
90
      break;
2182
2183
0
    case Type::BlockPointer:
2184
0
      type = cast<BlockPointerType>(ty)->getPointeeType();
2185
0
      break;
2186
2187
3
    case Type::LValueReference:
2188
3
    case Type::RValueReference:
2189
3
      type = cast<ReferenceType>(ty)->getPointeeType();
2190
3
      break;
2191
2192
0
    case Type::MemberPointer:
2193
0
      type = cast<MemberPointerType>(ty)->getPointeeType();
2194
0
      break;
2195
2196
2
    case Type::ConstantArray:
2197
12
    case Type::IncompleteArray:
2198
      // Losing element qualification here is fine.
2199
12
      type = cast<ArrayType>(ty)->getElementType();
2200
12
      break;
2201
2202
3.79k
    case Type::VariableArray: {
2203
      // Losing element qualification here is fine.
2204
3.79k
      const VariableArrayType *vat = cast<VariableArrayType>(ty);
2205
2206
      // Unknown size indication requires no size computation.
2207
      // Otherwise, evaluate and record it.
2208
3.79k
      if (const Expr *size = vat->getSizeExpr()) {
2209
        // It's possible that we might have emitted this already,
2210
        // e.g. with a typedef and a pointer to it.
2211
3.79k
        llvm::Value *&entry = VLASizeMap[size];
2212
3.79k
        if (!entry) {
2213
3.43k
          llvm::Value *Size = EmitScalarExpr(size);
2214
2215
          // C11 6.7.6.2p5:
2216
          //   If the size is an expression that is not an integer constant
2217
          //   expression [...] each time it is evaluated it shall have a value
2218
          //   greater than zero.
2219
3.43k
          if (SanOpts.has(SanitizerKind::VLABound) &&
2220
3.43k
              
size->getType()->isSignedIntegerType()2
) {
2221
2
            SanitizerScope SanScope(this);
2222
2
            llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
2223
2
            llvm::Constant *StaticArgs[] = {
2224
2
                EmitCheckSourceLocation(size->getBeginLoc()),
2225
2
                EmitCheckTypeDescriptor(size->getType())};
2226
2
            EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero),
2227
2
                                     SanitizerKind::VLABound),
2228
2
                      SanitizerHandler::VLABoundNotPositive, StaticArgs, Size);
2229
2
          }
2230
2231
          // Always zexting here would be wrong if it weren't
2232
          // undefined behavior to have a negative bound.
2233
3.43k
          entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
2234
3.43k
        }
2235
3.79k
      }
2236
3.79k
      type = vat->getElementType();
2237
3.79k
      break;
2238
2
    }
2239
2240
1
    case Type::FunctionProto:
2241
1
    case Type::FunctionNoProto:
2242
1
      type = cast<FunctionType>(ty)->getReturnType();
2243
1
      break;
2244
2245
42
    case Type::Paren:
2246
44
    case Type::TypeOf:
2247
44
    case Type::UnaryTransform:
2248
44
    case Type::Attributed:
2249
44
    case Type::SubstTemplateTypeParm:
2250
44
    case Type::MacroQualified:
2251
      // Keep walking after single level desugaring.
2252
44
      type = type.getSingleStepDesugaredType(getContext());
2253
44
      break;
2254
2255
28
    case Type::Typedef:
2256
28
    case Type::Decltype:
2257
28
    case Type::Auto:
2258
28
    case Type::DeducedTemplateSpecialization:
2259
      // Stop walking: nothing to do.
2260
28
      return;
2261
2262
13
    case Type::TypeOfExpr:
2263
      // Stop walking: emit typeof expression.
2264
13
      EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
2265
13
      return;
2266
2267
1
    case Type::Atomic:
2268
1
      type = cast<AtomicType>(ty)->getValueType();
2269
1
      break;
2270
2271
0
    case Type::Pipe:
2272
0
      type = cast<PipeType>(ty)->getElementType();
2273
0
      break;
2274
4.05k
    }
2275
4.05k
  } while (
type->isVariablyModifiedType()4.01k
);
2276
2.85k
}
2277
2278
1.32k
Address CodeGenFunction::EmitVAListRef(const Expr* E) {
2279
1.32k
  if (getContext().getBuiltinVaListType()->isArrayType())
2280
531
    return EmitPointerWithAlignment(E);
2281
797
  return EmitLValue(E).getAddress(*this);
2282
1.32k
}
2283
2284
40
Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
2285
40
  return EmitLValue(E).getAddress(*this);
2286
40
}
2287
2288
void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
2289
6.40k
                                              const APValue &Init) {
2290
6.40k
  assert(Init.hasValue() && "Invalid DeclRefExpr initializer!");
2291
6.40k
  if (CGDebugInfo *Dbg = getDebugInfo())
2292
3.62k
    if (CGM.getCodeGenOpts().hasReducedDebugInfo())
2293
3.59k
      Dbg->EmitGlobalVariable(E->getDecl(), Init);
2294
6.40k
}
2295
2296
CodeGenFunction::PeepholeProtection
2297
1.65k
CodeGenFunction::protectFromPeepholes(RValue rvalue) {
2298
  // At the moment, the only aggressive peephole we do in IR gen
2299
  // is trunc(zext) folding, but if we add more, we can easily
2300
  // extend this protection.
2301
2302
1.65k
  if (!rvalue.isScalar()) 
return PeepholeProtection()77
;
2303
1.58k
  llvm::Value *value = rvalue.getScalarVal();
2304
1.58k
  if (!isa<llvm::ZExtInst>(value)) 
return PeepholeProtection()1.50k
;
2305
2306
  // Just make an extra bitcast.
2307
77
  assert(HaveInsertPoint());
2308
0
  llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
2309
77
                                                  Builder.GetInsertBlock());
2310
2311
77
  PeepholeProtection protection;
2312
77
  protection.Inst = inst;
2313
77
  return protection;
2314
1.58k
}
2315
2316
1.65k
void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
2317
1.65k
  if (!protection.Inst) 
return1.58k
;
2318
2319
  // In theory, we could try to duplicate the peepholes now, but whatever.
2320
77
  protection.Inst->eraseFromParent();
2321
77
}
2322
2323
void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
2324
                                              QualType Ty, SourceLocation Loc,
2325
                                              SourceLocation AssumptionLoc,
2326
                                              llvm::Value *Alignment,
2327
446
                                              llvm::Value *OffsetValue) {
2328
446
  if (Alignment->getType() != IntPtrTy)
2329
218
    Alignment =
2330
218
        Builder.CreateIntCast(Alignment, IntPtrTy, false, "casted.align");
2331
446
  if (OffsetValue && 
OffsetValue->getType() != IntPtrTy16
)
2332
5
    OffsetValue =
2333
5
        Builder.CreateIntCast(OffsetValue, IntPtrTy, true, "casted.offset");
2334
446
  llvm::Value *TheCheck = nullptr;
2335
446
  if (SanOpts.has(SanitizerKind::Alignment)) {
2336
33
    llvm::Value *PtrIntValue =
2337
33
        Builder.CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
2338
2339
33
    if (OffsetValue) {
2340
9
      bool IsOffsetZero = false;
2341
9
      if (const auto *CI = dyn_cast<llvm::ConstantInt>(OffsetValue))
2342
6
        IsOffsetZero = CI->isZero();
2343
2344
9
      if (!IsOffsetZero)
2345
9
        PtrIntValue = Builder.CreateSub(PtrIntValue, OffsetValue, "offsetptr");
2346
9
    }
2347
2348
33
    llvm::Value *Zero = llvm::ConstantInt::get(IntPtrTy, 0);
2349
33
    llvm::Value *Mask =
2350
33
        Builder.CreateSub(Alignment, llvm::ConstantInt::get(IntPtrTy, 1));
2351
33
    llvm::Value *MaskedPtr = Builder.CreateAnd(PtrIntValue, Mask, "maskedptr");
2352
33
    TheCheck = Builder.CreateICmpEQ(MaskedPtr, Zero, "maskcond");
2353
33
  }
2354
446
  llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption(
2355
446
      CGM.getDataLayout(), PtrValue, Alignment, OffsetValue);
2356
2357
446
  if (!SanOpts.has(SanitizerKind::Alignment))
2358
413
    return;
2359
33
  emitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2360
33
                               OffsetValue, TheCheck, Assumption);
2361
33
}
2362
2363
void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
2364
                                              const Expr *E,
2365
                                              SourceLocation AssumptionLoc,
2366
                                              llvm::Value *Alignment,
2367
412
                                              llvm::Value *OffsetValue) {
2368
412
  if (auto *CE = dyn_cast<CastExpr>(E))
2369
172
    E = CE->getSubExprAsWritten();
2370
412
  QualType Ty = E->getType();
2371
412
  SourceLocation Loc = E->getExprLoc();
2372
2373
412
  emitAlignmentAssumption(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2374
412
                          OffsetValue);
2375
412
}
2376
2377
llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Function *AnnotationFn,
2378
                                                 llvm::Value *AnnotatedVal,
2379
                                                 StringRef AnnotationStr,
2380
                                                 SourceLocation Location,
2381
28
                                                 const AnnotateAttr *Attr) {
2382
28
  SmallVector<llvm::Value *, 5> Args = {
2383
28
      AnnotatedVal,
2384
28
      Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
2385
28
      Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
2386
28
      CGM.EmitAnnotationLineNo(Location),
2387
28
  };
2388
28
  if (Attr)
2389
21
    Args.push_back(CGM.EmitAnnotationArgs(Attr));
2390
28
  return Builder.CreateCall(AnnotationFn, Args);
2391
28
}
2392
2393
8
void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
2394
8
  assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2395
  // FIXME We create a new bitcast for every annotation because that's what
2396
  // llvm-gcc was doing.
2397
0
  for (const auto *I : D->specific_attrs<AnnotateAttr>())
2398
12
    EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
2399
12
                       Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
2400
12
                       I->getAnnotation(), D->getLocation(), I);
2401
8
}
2402
2403
Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
2404
5
                                              Address Addr) {
2405
5
  assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2406
0
  llvm::Value *V = Addr.getPointer();
2407
5
  llvm::Type *VTy = V->getType();
2408
5
  auto *PTy = dyn_cast<llvm::PointerType>(VTy);
2409
5
  unsigned AS = PTy ? PTy->getAddressSpace() : 
00
;
2410
5
  llvm::PointerType *IntrinTy =
2411
5
      llvm::PointerType::getWithSamePointeeType(CGM.Int8PtrTy, AS);
2412
5
  llvm::Function *F =
2413
5
      CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation, IntrinTy);
2414
2415
9
  for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
2416
    // FIXME Always emit the cast inst so we can differentiate between
2417
    // annotation on the first field of a struct and annotation on the struct
2418
    // itself.
2419
9
    if (VTy != IntrinTy)
2420
9
      V = Builder.CreateBitCast(V, IntrinTy);
2421
9
    V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation(), I);
2422
9
    V = Builder.CreateBitCast(V, VTy);
2423
9
  }
2424
2425
5
  return Address(V, Addr.getAlignment());
2426
5
}
2427
2428
69.1k
CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
2429
2430
CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
2431
58.9k
    : CGF(CGF) {
2432
58.9k
  assert(!CGF->IsSanitizerScope);
2433
0
  CGF->IsSanitizerScope = true;
2434
58.9k
}
2435
2436
58.9k
CodeGenFunction::SanitizerScope::~SanitizerScope() {
2437
58.9k
  CGF->IsSanitizerScope = false;
2438
58.9k
}
2439
2440
void CodeGenFunction::InsertHelper(llvm::Instruction *I,
2441
                                   const llvm::Twine &Name,
2442
                                   llvm::BasicBlock *BB,
2443
6.92M
                                   llvm::BasicBlock::iterator InsertPt) const {
2444
6.92M
  LoopStack.InsertHelper(I);
2445
6.92M
  if (IsSanitizerScope)
2446
15.4k
    CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
2447
6.92M
}
2448
2449
void CGBuilderInserter::InsertHelper(
2450
    llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
2451
6.93M
    llvm::BasicBlock::iterator InsertPt) const {
2452
6.93M
  llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
2453
6.93M
  if (CGF)
2454
6.92M
    CGF->InsertHelper(I, Name, BB, InsertPt);
2455
6.93M
}
2456
2457
// Emits an error if we don't have a valid set of target features for the
2458
// called function.
2459
void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
2460
115k
                                          const FunctionDecl *TargetDecl) {
2461
115k
  return checkTargetFeatures(E->getBeginLoc(), TargetDecl);
2462
115k
}
2463
2464
// Emits an error if we don't have a valid set of target features for the
2465
// called function.
2466
void CodeGenFunction::checkTargetFeatures(SourceLocation Loc,
2467
128k
                                          const FunctionDecl *TargetDecl) {
2468
  // Early exit if this is an indirect call.
2469
128k
  if (!TargetDecl)
2470
0
    return;
2471
2472
  // Get the current enclosing function if it exists. If it doesn't
2473
  // we can't check the target features anyhow.
2474
128k
  const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
2475
128k
  if (!FD)
2476
0
    return;
2477
2478
  // Grab the required features for the call. For a builtin this is listed in
2479
  // the td file with the default cpu, for an always_inline function this is any
2480
  // listed cpu and any listed features.
2481
128k
  unsigned BuiltinID = TargetDecl->getBuiltinID();
2482
128k
  std::string MissingFeature;
2483
128k
  llvm::StringMap<bool> CallerFeatureMap;
2484
128k
  CGM.getContext().getFunctionFeatureMap(CallerFeatureMap, FD);
2485
128k
  if (BuiltinID) {
2486
115k
    StringRef FeatureList(
2487
115k
        CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID));
2488
    // Return if the builtin doesn't have any required features.
2489
115k
    if (FeatureList.empty())
2490
49.6k
      return;
2491
65.6k
    assert(FeatureList.find(' ') == StringRef::npos &&
2492
65.6k
           "Space in feature list");
2493
0
    TargetFeatures TF(CallerFeatureMap);
2494
65.6k
    if (!TF.hasRequiredFeatures(FeatureList))
2495
623
      CGM.getDiags().Report(Loc, diag::err_builtin_needs_feature)
2496
623
          << TargetDecl->getDeclName() << FeatureList;
2497
65.6k
  } else 
if (13.3k
!TargetDecl->isMultiVersion()13.3k
&&
2498
13.3k
             TargetDecl->hasAttr<TargetAttr>()) {
2499
    // Get the required features for the callee.
2500
2501
13.3k
    const TargetAttr *TD = TargetDecl->getAttr<TargetAttr>();
2502
13.3k
    ParsedTargetAttr ParsedAttr =
2503
13.3k
        CGM.getContext().filterFunctionTargetAttrs(TD);
2504
2505
13.3k
    SmallVector<StringRef, 1> ReqFeatures;
2506
13.3k
    llvm::StringMap<bool> CalleeFeatureMap;
2507
13.3k
    CGM.getContext().getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
2508
2509
15.0k
    for (const auto &F : ParsedAttr.Features) {
2510
15.0k
      if (F[0] == '+' && CalleeFeatureMap.lookup(F.substr(1)))
2511
15.0k
        ReqFeatures.push_back(StringRef(F).substr(1));
2512
15.0k
    }
2513
2514
213k
    for (const auto &F : CalleeFeatureMap) {
2515
      // Only positive features are "required".
2516
213k
      if (F.getValue())
2517
213k
        ReqFeatures.push_back(F.getKey());
2518
213k
    }
2519
228k
    if (
!llvm::all_of(ReqFeatures, [&](StringRef Feature) 13.3k
{
2520
228k
      if (!CallerFeatureMap.lookup(Feature)) {
2521
19
        MissingFeature = Feature.str();
2522
19
        return false;
2523
19
      }
2524
228k
      return true;
2525
228k
    }))
2526
19
      CGM.getDiags().Report(Loc, diag::err_function_needs_feature)
2527
19
          << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
2528
13.3k
  }
2529
128k
}
2530
2531
87
void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
2532
87
  if (!CGM.getCodeGenOpts().SanitizeStats)
2533
77
    return;
2534
2535
10
  llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
2536
10
  IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
2537
10
  CGM.getSanStats().create(IRB, SSK);
2538
10
}
2539
2540
llvm::Value *
2541
272
CodeGenFunction::FormResolverCondition(const MultiVersionResolverOption &RO) {
2542
272
  llvm::Value *Condition = nullptr;
2543
2544
272
  if (!RO.Conditions.Architecture.empty())
2545
92
    Condition = EmitX86CpuIs(RO.Conditions.Architecture);
2546
2547
272
  if (!RO.Conditions.Features.empty()) {
2548
111
    llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Conditions.Features);
2549
111
    Condition =
2550
111
        Condition ? 
Builder.CreateAnd(Condition, FeatureCond)2
:
FeatureCond109
;
2551
111
  }
2552
272
  return Condition;
2553
272
}
2554
2555
static void CreateMultiVersionResolverReturn(CodeGenModule &CGM,
2556
                                             llvm::Function *Resolver,
2557
                                             CGBuilderTy &Builder,
2558
                                             llvm::Function *FuncToReturn,
2559
272
                                             bool SupportsIFunc) {
2560
272
  if (SupportsIFunc) {
2561
136
    Builder.CreateRet(FuncToReturn);
2562
136
    return;
2563
136
  }
2564
2565
136
  llvm::SmallVector<llvm::Value *, 10> Args;
2566
136
  llvm::for_each(Resolver->args(),
2567
138
                 [&](llvm::Argument &Arg) { Args.push_back(&Arg); });
2568
2569
136
  llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args);
2570
136
  Result->setTailCallKind(llvm::CallInst::TCK_MustTail);
2571
2572
136
  if (Resolver->getReturnType()->isVoidTy())
2573
32
    Builder.CreateRetVoid();
2574
104
  else
2575
104
    Builder.CreateRet(Result);
2576
136
}
2577
2578
void CodeGenFunction::EmitMultiVersionResolver(
2579
87
    llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) {
2580
87
  assert(getContext().getTargetInfo().getTriple().isX86() &&
2581
87
         "Only implemented for x86 targets");
2582
2583
0
  bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
2584
2585
  // Main function's basic block.
2586
87
  llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
2587
87
  Builder.SetInsertPoint(CurBlock);
2588
87
  EmitX86CpuInit();
2589
2590
272
  for (const MultiVersionResolverOption &RO : Options) {
2591
272
    Builder.SetInsertPoint(CurBlock);
2592
272
    llvm::Value *Condition = FormResolverCondition(RO);
2593
2594
    // The 'default' or 'generic' case.
2595
272
    if (!Condition) {
2596
71
      assert(&RO == Options.end() - 1 &&
2597
71
             "Default or Generic case must be last");
2598
0
      CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
2599
71
                                       SupportsIFunc);
2600
71
      return;
2601
71
    }
2602
2603
201
    llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
2604
201
    CGBuilderTy RetBuilder(*this, RetBlock);
2605
201
    CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
2606
201
                                     SupportsIFunc);
2607
201
    CurBlock = createBasicBlock("resolver_else", Resolver);
2608
201
    Builder.CreateCondBr(Condition, RetBlock, CurBlock);
2609
201
  }
2610
2611
  // If no generic/default, emit an unreachable.
2612
16
  Builder.SetInsertPoint(CurBlock);
2613
16
  llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
2614
16
  TrapCall->setDoesNotReturn();
2615
16
  TrapCall->setDoesNotThrow();
2616
16
  Builder.CreateUnreachable();
2617
16
  Builder.ClearInsertionPoint();
2618
16
}
2619
2620
// Loc - where the diagnostic will point, where in the source code this
2621
//  alignment has failed.
2622
// SecondaryLoc - if present (will be present if sufficiently different from
2623
//  Loc), the diagnostic will additionally point a "Note:" to this location.
2624
//  It should be the location where the __attribute__((assume_aligned))
2625
//  was written e.g.
2626
void CodeGenFunction::emitAlignmentAssumptionCheck(
2627
    llvm::Value *Ptr, QualType Ty, SourceLocation Loc,
2628
    SourceLocation SecondaryLoc, llvm::Value *Alignment,
2629
    llvm::Value *OffsetValue, llvm::Value *TheCheck,
2630
33
    llvm::Instruction *Assumption) {
2631
33
  assert(Assumption && isa<llvm::CallInst>(Assumption) &&
2632
33
         cast<llvm::CallInst>(Assumption)->getCalledOperand() ==
2633
33
             llvm::Intrinsic::getDeclaration(
2634
33
                 Builder.GetInsertBlock()->getParent()->getParent(),
2635
33
                 llvm::Intrinsic::assume) &&
2636
33
         "Assumption should be a call to llvm.assume().");
2637
0
  assert(&(Builder.GetInsertBlock()->back()) == Assumption &&
2638
33
         "Assumption should be the last instruction of the basic block, "
2639
33
         "since the basic block is still being generated.");
2640
2641
33
  if (!SanOpts.has(SanitizerKind::Alignment))
2642
0
    return;
2643
2644
  // Don't check pointers to volatile data. The behavior here is implementation-
2645
  // defined.
2646
33
  if (Ty->getPointeeType().isVolatileQualified())
2647
1
    return;
2648
2649
  // We need to temorairly remove the assumption so we can insert the
2650
  // sanitizer check before it, else the check will be dropped by optimizations.
2651
32
  Assumption->removeFromParent();
2652
2653
32
  {
2654
32
    SanitizerScope SanScope(this);
2655
2656
32
    if (!OffsetValue)
2657
23
      OffsetValue = Builder.getInt1(0); // no offset.
2658
2659
32
    llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc),
2660
32
                                    EmitCheckSourceLocation(SecondaryLoc),
2661
32
                                    EmitCheckTypeDescriptor(Ty)};
2662
32
    llvm::Value *DynamicData[] = {EmitCheckValue(Ptr),
2663
32
                                  EmitCheckValue(Alignment),
2664
32
                                  EmitCheckValue(OffsetValue)};
2665
32
    EmitCheck({std::make_pair(TheCheck, SanitizerKind::Alignment)},
2666
32
              SanitizerHandler::AlignmentAssumption, StaticData, DynamicData);
2667
32
  }
2668
2669
  // We are now in the (new, empty) "cont" basic block.
2670
  // Reintroduce the assumption.
2671
32
  Builder.Insert(Assumption);
2672
  // FIXME: Assumption still has it's original basic block as it's Parent.
2673
32
}
2674
2675
70.1k
llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) {
2676
70.1k
  if (CGDebugInfo *DI = getDebugInfo())
2677
31.3k
    return DI->SourceLocToDebugLoc(Location);
2678
2679
38.7k
  return llvm::DebugLoc();
2680
70.1k
}
2681
2682
llvm::Value *
2683
CodeGenFunction::emitCondLikelihoodViaExpectIntrinsic(llvm::Value *Cond,
2684
152k
                                                      Stmt::Likelihood LH) {
2685
152k
  switch (LH) {
2686
152k
  case Stmt::LH_None:
2687
152k
    return Cond;
2688
17
  case Stmt::LH_Likely:
2689
58
  case Stmt::LH_Unlikely:
2690
    // Don't generate llvm.expect on -O0 as the backend won't use it for
2691
    // anything.
2692
58
    if (CGM.getCodeGenOpts().OptimizationLevel == 0)
2693
0
      return Cond;
2694
58
    llvm::Type *CondTy = Cond->getType();
2695
58
    assert(CondTy->isIntegerTy(1) && "expecting condition to be a boolean");
2696
0
    llvm::Function *FnExpect =
2697
58
        CGM.getIntrinsic(llvm::Intrinsic::expect, CondTy);
2698
58
    llvm::Value *ExpectedValueOfCond =
2699
58
        llvm::ConstantInt::getBool(CondTy, LH == Stmt::LH_Likely);
2700
58
    return Builder.CreateCall(FnExpect, {Cond, ExpectedValueOfCond},
2701
58
                              Cond->getName() + ".expval");
2702
152k
  }
2703
0
  llvm_unreachable("Unknown Likelihood");
2704
0
}