1 //===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===//
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 contains code to emit Stmt nodes as LLVM code.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CGDebugInfo.h"
14 #include "CGOpenMPRuntime.h"
15 #include "CodeGenFunction.h"
16 #include "CodeGenModule.h"
17 #include "TargetInfo.h"
18 #include "clang/AST/Attr.h"
19 #include "clang/AST/StmtVisitor.h"
20 #include "clang/Basic/Builtins.h"
21 #include "clang/Basic/DiagnosticSema.h"
22 #include "clang/Basic/PrettyStackTrace.h"
23 #include "clang/Basic/SourceManager.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/InlineAsm.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/MDBuilder.h"
31 #include "llvm/Support/SaveAndRestore.h"
32 
33 using namespace clang;
34 using namespace CodeGen;
35 
36 //===----------------------------------------------------------------------===//
37 //                              Statement Emission
38 //===----------------------------------------------------------------------===//
39 
40 void CodeGenFunction::EmitStopPoint(const Stmt *S) {
41   if (CGDebugInfo *DI = getDebugInfo()) {
42     SourceLocation Loc;
43     Loc = S->getBeginLoc();
44     DI->EmitLocation(Builder, Loc);
45 
46     LastStopPoint = Loc;
47   }
48 }
49 
50 void CodeGenFunction::EmitStmt(const Stmt *S, ArrayRef<const Attr *> Attrs) {
51   assert(S && "Null statement?");
52   PGO.setCurrentStmt(S);
53 
54   // These statements have their own debug info handling.
55   if (EmitSimpleStmt(S, Attrs))
56     return;
57 
58   // Check if we are generating unreachable code.
59   if (!HaveInsertPoint()) {
60     // If so, and the statement doesn't contain a label, then we do not need to
61     // generate actual code. This is safe because (1) the current point is
62     // unreachable, so we don't need to execute the code, and (2) we've already
63     // handled the statements which update internal data structures (like the
64     // local variable map) which could be used by subsequent statements.
65     if (!ContainsLabel(S)) {
66       // Verify that any decl statements were handled as simple, they may be in
67       // scope of subsequent reachable statements.
68       assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
69       return;
70     }
71 
72     // Otherwise, make a new block to hold the code.
73     EnsureInsertPoint();
74   }
75 
76   // Generate a stoppoint if we are emitting debug info.
77   EmitStopPoint(S);
78 
79   // Ignore all OpenMP directives except for simd if OpenMP with Simd is
80   // enabled.
81   if (getLangOpts().OpenMP && getLangOpts().OpenMPSimd) {
82     if (const auto *D = dyn_cast<OMPExecutableDirective>(S)) {
83       EmitSimpleOMPExecutableDirective(*D);
84       return;
85     }
86   }
87 
88   switch (S->getStmtClass()) {
89   case Stmt::NoStmtClass:
90   case Stmt::CXXCatchStmtClass:
91   case Stmt::SEHExceptStmtClass:
92   case Stmt::SEHFinallyStmtClass:
93   case Stmt::MSDependentExistsStmtClass:
94     llvm_unreachable("invalid statement class to emit generically");
95   case Stmt::NullStmtClass:
96   case Stmt::CompoundStmtClass:
97   case Stmt::DeclStmtClass:
98   case Stmt::LabelStmtClass:
99   case Stmt::AttributedStmtClass:
100   case Stmt::GotoStmtClass:
101   case Stmt::BreakStmtClass:
102   case Stmt::ContinueStmtClass:
103   case Stmt::DefaultStmtClass:
104   case Stmt::CaseStmtClass:
105   case Stmt::SEHLeaveStmtClass:
106     llvm_unreachable("should have emitted these statements as simple");
107 
108 #define STMT(Type, Base)
109 #define ABSTRACT_STMT(Op)
110 #define EXPR(Type, Base) \
111   case Stmt::Type##Class:
112 #include "clang/AST/StmtNodes.inc"
113   {
114     // Remember the block we came in on.
115     llvm::BasicBlock *incoming = Builder.GetInsertBlock();
116     assert(incoming && "expression emission must have an insertion point");
117 
118     EmitIgnoredExpr(cast<Expr>(S));
119 
120     llvm::BasicBlock *outgoing = Builder.GetInsertBlock();
121     assert(outgoing && "expression emission cleared block!");
122 
123     // The expression emitters assume (reasonably!) that the insertion
124     // point is always set.  To maintain that, the call-emission code
125     // for noreturn functions has to enter a new block with no
126     // predecessors.  We want to kill that block and mark the current
127     // insertion point unreachable in the common case of a call like
128     // "exit();".  Since expression emission doesn't otherwise create
129     // blocks with no predecessors, we can just test for that.
130     // However, we must be careful not to do this to our incoming
131     // block, because *statement* emission does sometimes create
132     // reachable blocks which will have no predecessors until later in
133     // the function.  This occurs with, e.g., labels that are not
134     // reachable by fallthrough.
135     if (incoming != outgoing && outgoing->use_empty()) {
136       outgoing->eraseFromParent();
137       Builder.ClearInsertionPoint();
138     }
139     break;
140   }
141 
142   case Stmt::IndirectGotoStmtClass:
143     EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
144 
145   case Stmt::IfStmtClass:      EmitIfStmt(cast<IfStmt>(*S));              break;
146   case Stmt::WhileStmtClass:   EmitWhileStmt(cast<WhileStmt>(*S), Attrs); break;
147   case Stmt::DoStmtClass:      EmitDoStmt(cast<DoStmt>(*S), Attrs);       break;
148   case Stmt::ForStmtClass:     EmitForStmt(cast<ForStmt>(*S), Attrs);     break;
149 
150   case Stmt::ReturnStmtClass:  EmitReturnStmt(cast<ReturnStmt>(*S));      break;
151 
152   case Stmt::SwitchStmtClass:  EmitSwitchStmt(cast<SwitchStmt>(*S));      break;
153   case Stmt::GCCAsmStmtClass:  // Intentional fall-through.
154   case Stmt::MSAsmStmtClass:   EmitAsmStmt(cast<AsmStmt>(*S));            break;
155   case Stmt::CoroutineBodyStmtClass:
156     EmitCoroutineBody(cast<CoroutineBodyStmt>(*S));
157     break;
158   case Stmt::CoreturnStmtClass:
159     EmitCoreturnStmt(cast<CoreturnStmt>(*S));
160     break;
161   case Stmt::CapturedStmtClass: {
162     const CapturedStmt *CS = cast<CapturedStmt>(S);
163     EmitCapturedStmt(*CS, CS->getCapturedRegionKind());
164     }
165     break;
166   case Stmt::ObjCAtTryStmtClass:
167     EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
168     break;
169   case Stmt::ObjCAtCatchStmtClass:
170     llvm_unreachable(
171                     "@catch statements should be handled by EmitObjCAtTryStmt");
172   case Stmt::ObjCAtFinallyStmtClass:
173     llvm_unreachable(
174                   "@finally statements should be handled by EmitObjCAtTryStmt");
175   case Stmt::ObjCAtThrowStmtClass:
176     EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
177     break;
178   case Stmt::ObjCAtSynchronizedStmtClass:
179     EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
180     break;
181   case Stmt::ObjCForCollectionStmtClass:
182     EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
183     break;
184   case Stmt::ObjCAutoreleasePoolStmtClass:
185     EmitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(*S));
186     break;
187 
188   case Stmt::CXXTryStmtClass:
189     EmitCXXTryStmt(cast<CXXTryStmt>(*S));
190     break;
191   case Stmt::CXXForRangeStmtClass:
192     EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*S), Attrs);
193     break;
194   case Stmt::SEHTryStmtClass:
195     EmitSEHTryStmt(cast<SEHTryStmt>(*S));
196     break;
197   case Stmt::OMPParallelDirectiveClass:
198     EmitOMPParallelDirective(cast<OMPParallelDirective>(*S));
199     break;
200   case Stmt::OMPSimdDirectiveClass:
201     EmitOMPSimdDirective(cast<OMPSimdDirective>(*S));
202     break;
203   case Stmt::OMPForDirectiveClass:
204     EmitOMPForDirective(cast<OMPForDirective>(*S));
205     break;
206   case Stmt::OMPForSimdDirectiveClass:
207     EmitOMPForSimdDirective(cast<OMPForSimdDirective>(*S));
208     break;
209   case Stmt::OMPSectionsDirectiveClass:
210     EmitOMPSectionsDirective(cast<OMPSectionsDirective>(*S));
211     break;
212   case Stmt::OMPSectionDirectiveClass:
213     EmitOMPSectionDirective(cast<OMPSectionDirective>(*S));
214     break;
215   case Stmt::OMPSingleDirectiveClass:
216     EmitOMPSingleDirective(cast<OMPSingleDirective>(*S));
217     break;
218   case Stmt::OMPMasterDirectiveClass:
219     EmitOMPMasterDirective(cast<OMPMasterDirective>(*S));
220     break;
221   case Stmt::OMPCriticalDirectiveClass:
222     EmitOMPCriticalDirective(cast<OMPCriticalDirective>(*S));
223     break;
224   case Stmt::OMPParallelForDirectiveClass:
225     EmitOMPParallelForDirective(cast<OMPParallelForDirective>(*S));
226     break;
227   case Stmt::OMPParallelForSimdDirectiveClass:
228     EmitOMPParallelForSimdDirective(cast<OMPParallelForSimdDirective>(*S));
229     break;
230   case Stmt::OMPParallelMasterDirectiveClass:
231     EmitOMPParallelMasterDirective(cast<OMPParallelMasterDirective>(*S));
232     break;
233   case Stmt::OMPParallelSectionsDirectiveClass:
234     EmitOMPParallelSectionsDirective(cast<OMPParallelSectionsDirective>(*S));
235     break;
236   case Stmt::OMPTaskDirectiveClass:
237     EmitOMPTaskDirective(cast<OMPTaskDirective>(*S));
238     break;
239   case Stmt::OMPTaskyieldDirectiveClass:
240     EmitOMPTaskyieldDirective(cast<OMPTaskyieldDirective>(*S));
241     break;
242   case Stmt::OMPBarrierDirectiveClass:
243     EmitOMPBarrierDirective(cast<OMPBarrierDirective>(*S));
244     break;
245   case Stmt::OMPTaskwaitDirectiveClass:
246     EmitOMPTaskwaitDirective(cast<OMPTaskwaitDirective>(*S));
247     break;
248   case Stmt::OMPTaskgroupDirectiveClass:
249     EmitOMPTaskgroupDirective(cast<OMPTaskgroupDirective>(*S));
250     break;
251   case Stmt::OMPFlushDirectiveClass:
252     EmitOMPFlushDirective(cast<OMPFlushDirective>(*S));
253     break;
254   case Stmt::OMPDepobjDirectiveClass:
255     EmitOMPDepobjDirective(cast<OMPDepobjDirective>(*S));
256     break;
257   case Stmt::OMPScanDirectiveClass:
258     EmitOMPScanDirective(cast<OMPScanDirective>(*S));
259     break;
260   case Stmt::OMPOrderedDirectiveClass:
261     EmitOMPOrderedDirective(cast<OMPOrderedDirective>(*S));
262     break;
263   case Stmt::OMPAtomicDirectiveClass:
264     EmitOMPAtomicDirective(cast<OMPAtomicDirective>(*S));
265     break;
266   case Stmt::OMPTargetDirectiveClass:
267     EmitOMPTargetDirective(cast<OMPTargetDirective>(*S));
268     break;
269   case Stmt::OMPTeamsDirectiveClass:
270     EmitOMPTeamsDirective(cast<OMPTeamsDirective>(*S));
271     break;
272   case Stmt::OMPCancellationPointDirectiveClass:
273     EmitOMPCancellationPointDirective(cast<OMPCancellationPointDirective>(*S));
274     break;
275   case Stmt::OMPCancelDirectiveClass:
276     EmitOMPCancelDirective(cast<OMPCancelDirective>(*S));
277     break;
278   case Stmt::OMPTargetDataDirectiveClass:
279     EmitOMPTargetDataDirective(cast<OMPTargetDataDirective>(*S));
280     break;
281   case Stmt::OMPTargetEnterDataDirectiveClass:
282     EmitOMPTargetEnterDataDirective(cast<OMPTargetEnterDataDirective>(*S));
283     break;
284   case Stmt::OMPTargetExitDataDirectiveClass:
285     EmitOMPTargetExitDataDirective(cast<OMPTargetExitDataDirective>(*S));
286     break;
287   case Stmt::OMPTargetParallelDirectiveClass:
288     EmitOMPTargetParallelDirective(cast<OMPTargetParallelDirective>(*S));
289     break;
290   case Stmt::OMPTargetParallelForDirectiveClass:
291     EmitOMPTargetParallelForDirective(cast<OMPTargetParallelForDirective>(*S));
292     break;
293   case Stmt::OMPTaskLoopDirectiveClass:
294     EmitOMPTaskLoopDirective(cast<OMPTaskLoopDirective>(*S));
295     break;
296   case Stmt::OMPTaskLoopSimdDirectiveClass:
297     EmitOMPTaskLoopSimdDirective(cast<OMPTaskLoopSimdDirective>(*S));
298     break;
299   case Stmt::OMPMasterTaskLoopDirectiveClass:
300     EmitOMPMasterTaskLoopDirective(cast<OMPMasterTaskLoopDirective>(*S));
301     break;
302   case Stmt::OMPMasterTaskLoopSimdDirectiveClass:
303     EmitOMPMasterTaskLoopSimdDirective(
304         cast<OMPMasterTaskLoopSimdDirective>(*S));
305     break;
306   case Stmt::OMPParallelMasterTaskLoopDirectiveClass:
307     EmitOMPParallelMasterTaskLoopDirective(
308         cast<OMPParallelMasterTaskLoopDirective>(*S));
309     break;
310   case Stmt::OMPParallelMasterTaskLoopSimdDirectiveClass:
311     EmitOMPParallelMasterTaskLoopSimdDirective(
312         cast<OMPParallelMasterTaskLoopSimdDirective>(*S));
313     break;
314   case Stmt::OMPDistributeDirectiveClass:
315     EmitOMPDistributeDirective(cast<OMPDistributeDirective>(*S));
316     break;
317   case Stmt::OMPTargetUpdateDirectiveClass:
318     EmitOMPTargetUpdateDirective(cast<OMPTargetUpdateDirective>(*S));
319     break;
320   case Stmt::OMPDistributeParallelForDirectiveClass:
321     EmitOMPDistributeParallelForDirective(
322         cast<OMPDistributeParallelForDirective>(*S));
323     break;
324   case Stmt::OMPDistributeParallelForSimdDirectiveClass:
325     EmitOMPDistributeParallelForSimdDirective(
326         cast<OMPDistributeParallelForSimdDirective>(*S));
327     break;
328   case Stmt::OMPDistributeSimdDirectiveClass:
329     EmitOMPDistributeSimdDirective(cast<OMPDistributeSimdDirective>(*S));
330     break;
331   case Stmt::OMPTargetParallelForSimdDirectiveClass:
332     EmitOMPTargetParallelForSimdDirective(
333         cast<OMPTargetParallelForSimdDirective>(*S));
334     break;
335   case Stmt::OMPTargetSimdDirectiveClass:
336     EmitOMPTargetSimdDirective(cast<OMPTargetSimdDirective>(*S));
337     break;
338   case Stmt::OMPTeamsDistributeDirectiveClass:
339     EmitOMPTeamsDistributeDirective(cast<OMPTeamsDistributeDirective>(*S));
340     break;
341   case Stmt::OMPTeamsDistributeSimdDirectiveClass:
342     EmitOMPTeamsDistributeSimdDirective(
343         cast<OMPTeamsDistributeSimdDirective>(*S));
344     break;
345   case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
346     EmitOMPTeamsDistributeParallelForSimdDirective(
347         cast<OMPTeamsDistributeParallelForSimdDirective>(*S));
348     break;
349   case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
350     EmitOMPTeamsDistributeParallelForDirective(
351         cast<OMPTeamsDistributeParallelForDirective>(*S));
352     break;
353   case Stmt::OMPTargetTeamsDirectiveClass:
354     EmitOMPTargetTeamsDirective(cast<OMPTargetTeamsDirective>(*S));
355     break;
356   case Stmt::OMPTargetTeamsDistributeDirectiveClass:
357     EmitOMPTargetTeamsDistributeDirective(
358         cast<OMPTargetTeamsDistributeDirective>(*S));
359     break;
360   case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
361     EmitOMPTargetTeamsDistributeParallelForDirective(
362         cast<OMPTargetTeamsDistributeParallelForDirective>(*S));
363     break;
364   case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
365     EmitOMPTargetTeamsDistributeParallelForSimdDirective(
366         cast<OMPTargetTeamsDistributeParallelForSimdDirective>(*S));
367     break;
368   case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
369     EmitOMPTargetTeamsDistributeSimdDirective(
370         cast<OMPTargetTeamsDistributeSimdDirective>(*S));
371     break;
372   }
373 }
374 
375 bool CodeGenFunction::EmitSimpleStmt(const Stmt *S,
376                                      ArrayRef<const Attr *> Attrs) {
377   switch (S->getStmtClass()) {
378   default:
379     return false;
380   case Stmt::NullStmtClass:
381     break;
382   case Stmt::CompoundStmtClass:
383     EmitCompoundStmt(cast<CompoundStmt>(*S));
384     break;
385   case Stmt::DeclStmtClass:
386     EmitDeclStmt(cast<DeclStmt>(*S));
387     break;
388   case Stmt::LabelStmtClass:
389     EmitLabelStmt(cast<LabelStmt>(*S));
390     break;
391   case Stmt::AttributedStmtClass:
392     EmitAttributedStmt(cast<AttributedStmt>(*S));
393     break;
394   case Stmt::GotoStmtClass:
395     EmitGotoStmt(cast<GotoStmt>(*S));
396     break;
397   case Stmt::BreakStmtClass:
398     EmitBreakStmt(cast<BreakStmt>(*S));
399     break;
400   case Stmt::ContinueStmtClass:
401     EmitContinueStmt(cast<ContinueStmt>(*S));
402     break;
403   case Stmt::DefaultStmtClass:
404     EmitDefaultStmt(cast<DefaultStmt>(*S), Attrs);
405     break;
406   case Stmt::CaseStmtClass:
407     EmitCaseStmt(cast<CaseStmt>(*S), Attrs);
408     break;
409   case Stmt::SEHLeaveStmtClass:
410     EmitSEHLeaveStmt(cast<SEHLeaveStmt>(*S));
411     break;
412   }
413   return true;
414 }
415 
416 /// EmitCompoundStmt - Emit a compound statement {..} node.  If GetLast is true,
417 /// this captures the expression result of the last sub-statement and returns it
418 /// (for use by the statement expression extension).
419 Address CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
420                                           AggValueSlot AggSlot) {
421   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
422                              "LLVM IR generation of compound statement ('{}')");
423 
424   // Keep track of the current cleanup stack depth, including debug scopes.
425   LexicalScope Scope(*this, S.getSourceRange());
426 
427   return EmitCompoundStmtWithoutScope(S, GetLast, AggSlot);
428 }
429 
430 Address
431 CodeGenFunction::EmitCompoundStmtWithoutScope(const CompoundStmt &S,
432                                               bool GetLast,
433                                               AggValueSlot AggSlot) {
434 
435   const Stmt *ExprResult = S.getStmtExprResult();
436   assert((!GetLast || (GetLast && ExprResult)) &&
437          "If GetLast is true then the CompoundStmt must have a StmtExprResult");
438 
439   Address RetAlloca = Address::invalid();
440 
441   for (auto *CurStmt : S.body()) {
442     if (GetLast && ExprResult == CurStmt) {
443       // We have to special case labels here.  They are statements, but when put
444       // at the end of a statement expression, they yield the value of their
445       // subexpression.  Handle this by walking through all labels we encounter,
446       // emitting them before we evaluate the subexpr.
447       // Similar issues arise for attributed statements.
448       while (!isa<Expr>(ExprResult)) {
449         if (const auto *LS = dyn_cast<LabelStmt>(ExprResult)) {
450           EmitLabel(LS->getDecl());
451           ExprResult = LS->getSubStmt();
452         } else if (const auto *AS = dyn_cast<AttributedStmt>(ExprResult)) {
453           // FIXME: Update this if we ever have attributes that affect the
454           // semantics of an expression.
455           ExprResult = AS->getSubStmt();
456         } else {
457           llvm_unreachable("unknown value statement");
458         }
459       }
460 
461       EnsureInsertPoint();
462 
463       const Expr *E = cast<Expr>(ExprResult);
464       QualType ExprTy = E->getType();
465       if (hasAggregateEvaluationKind(ExprTy)) {
466         EmitAggExpr(E, AggSlot);
467       } else {
468         // We can't return an RValue here because there might be cleanups at
469         // the end of the StmtExpr.  Because of that, we have to emit the result
470         // here into a temporary alloca.
471         RetAlloca = CreateMemTemp(ExprTy);
472         EmitAnyExprToMem(E, RetAlloca, Qualifiers(),
473                          /*IsInit*/ false);
474       }
475     } else {
476       EmitStmt(CurStmt);
477     }
478   }
479 
480   return RetAlloca;
481 }
482 
483 void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
484   llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
485 
486   // If there is a cleanup stack, then we it isn't worth trying to
487   // simplify this block (we would need to remove it from the scope map
488   // and cleanup entry).
489   if (!EHStack.empty())
490     return;
491 
492   // Can only simplify direct branches.
493   if (!BI || !BI->isUnconditional())
494     return;
495 
496   // Can only simplify empty blocks.
497   if (BI->getIterator() != BB->begin())
498     return;
499 
500   BB->replaceAllUsesWith(BI->getSuccessor(0));
501   BI->eraseFromParent();
502   BB->eraseFromParent();
503 }
504 
505 void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
506   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
507 
508   // Fall out of the current block (if necessary).
509   EmitBranch(BB);
510 
511   if (IsFinished && BB->use_empty()) {
512     delete BB;
513     return;
514   }
515 
516   // Place the block after the current block, if possible, or else at
517   // the end of the function.
518   if (CurBB && CurBB->getParent())
519     CurFn->getBasicBlockList().insertAfter(CurBB->getIterator(), BB);
520   else
521     CurFn->getBasicBlockList().push_back(BB);
522   Builder.SetInsertPoint(BB);
523 }
524 
525 void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
526   // Emit a branch from the current block to the target one if this
527   // was a real block.  If this was just a fall-through block after a
528   // terminator, don't emit it.
529   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
530 
531   if (!CurBB || CurBB->getTerminator()) {
532     // If there is no insert point or the previous block is already
533     // terminated, don't touch it.
534   } else {
535     // Otherwise, create a fall-through branch.
536     Builder.CreateBr(Target);
537   }
538 
539   Builder.ClearInsertionPoint();
540 }
541 
542 void CodeGenFunction::EmitBlockAfterUses(llvm::BasicBlock *block) {
543   bool inserted = false;
544   for (llvm::User *u : block->users()) {
545     if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(u)) {
546       CurFn->getBasicBlockList().insertAfter(insn->getParent()->getIterator(),
547                                              block);
548       inserted = true;
549       break;
550     }
551   }
552 
553   if (!inserted)
554     CurFn->getBasicBlockList().push_back(block);
555 
556   Builder.SetInsertPoint(block);
557 }
558 
559 CodeGenFunction::JumpDest
560 CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) {
561   JumpDest &Dest = LabelMap[D];
562   if (Dest.isValid()) return Dest;
563 
564   // Create, but don't insert, the new block.
565   Dest = JumpDest(createBasicBlock(D->getName()),
566                   EHScopeStack::stable_iterator::invalid(),
567                   NextCleanupDestIndex++);
568   return Dest;
569 }
570 
571 void CodeGenFunction::EmitLabel(const LabelDecl *D) {
572   // Add this label to the current lexical scope if we're within any
573   // normal cleanups.  Jumps "in" to this label --- when permitted by
574   // the language --- may need to be routed around such cleanups.
575   if (EHStack.hasNormalCleanups() && CurLexicalScope)
576     CurLexicalScope->addLabel(D);
577 
578   JumpDest &Dest = LabelMap[D];
579 
580   // If we didn't need a forward reference to this label, just go
581   // ahead and create a destination at the current scope.
582   if (!Dest.isValid()) {
583     Dest = getJumpDestInCurrentScope(D->getName());
584 
585   // Otherwise, we need to give this label a target depth and remove
586   // it from the branch-fixups list.
587   } else {
588     assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
589     Dest.setScopeDepth(EHStack.stable_begin());
590     ResolveBranchFixups(Dest.getBlock());
591   }
592 
593   EmitBlock(Dest.getBlock());
594 
595   // Emit debug info for labels.
596   if (CGDebugInfo *DI = getDebugInfo()) {
597     if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
598       DI->setLocation(D->getLocation());
599       DI->EmitLabel(D, Builder);
600     }
601   }
602 
603   incrementProfileCounter(D->getStmt());
604 }
605 
606 /// Change the cleanup scope of the labels in this lexical scope to
607 /// match the scope of the enclosing context.
608 void CodeGenFunction::LexicalScope::rescopeLabels() {
609   assert(!Labels.empty());
610   EHScopeStack::stable_iterator innermostScope
611     = CGF.EHStack.getInnermostNormalCleanup();
612 
613   // Change the scope depth of all the labels.
614   for (SmallVectorImpl<const LabelDecl*>::const_iterator
615          i = Labels.begin(), e = Labels.end(); i != e; ++i) {
616     assert(CGF.LabelMap.count(*i));
617     JumpDest &dest = CGF.LabelMap.find(*i)->second;
618     assert(dest.getScopeDepth().isValid());
619     assert(innermostScope.encloses(dest.getScopeDepth()));
620     dest.setScopeDepth(innermostScope);
621   }
622 
623   // Reparent the labels if the new scope also has cleanups.
624   if (innermostScope != EHScopeStack::stable_end() && ParentScope) {
625     ParentScope->Labels.append(Labels.begin(), Labels.end());
626   }
627 }
628 
629 
630 void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
631   EmitLabel(S.getDecl());
632   EmitStmt(S.getSubStmt());
633 }
634 
635 void CodeGenFunction::EmitAttributedStmt(const AttributedStmt &S) {
636   bool nomerge = false;
637   for (const auto *A : S.getAttrs())
638     if (A->getKind() == attr::NoMerge) {
639       nomerge = true;
640       break;
641     }
642   SaveAndRestore<bool> save_nomerge(InNoMergeAttributedStmt, nomerge);
643   EmitStmt(S.getSubStmt(), S.getAttrs());
644 }
645 
646 void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
647   // If this code is reachable then emit a stop point (if generating
648   // debug info). We have to do this ourselves because we are on the
649   // "simple" statement path.
650   if (HaveInsertPoint())
651     EmitStopPoint(&S);
652 
653   EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel()));
654 }
655 
656 
657 void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
658   if (const LabelDecl *Target = S.getConstantTarget()) {
659     EmitBranchThroughCleanup(getJumpDestForLabel(Target));
660     return;
661   }
662 
663   // Ensure that we have an i8* for our PHI node.
664   llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
665                                          Int8PtrTy, "addr");
666   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
667 
668   // Get the basic block for the indirect goto.
669   llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
670 
671   // The first instruction in the block has to be the PHI for the switch dest,
672   // add an entry for this branch.
673   cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
674 
675   EmitBranch(IndGotoBB);
676 }
677 
678 void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
679   // C99 6.8.4.1: The first substatement is executed if the expression compares
680   // unequal to 0.  The condition must be a scalar type.
681   LexicalScope ConditionScope(*this, S.getCond()->getSourceRange());
682 
683   if (S.getInit())
684     EmitStmt(S.getInit());
685 
686   if (S.getConditionVariable())
687     EmitDecl(*S.getConditionVariable());
688 
689   // If the condition constant folds and can be elided, try to avoid emitting
690   // the condition and the dead arm of the if/else.
691   bool CondConstant;
692   if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant,
693                                    S.isConstexpr())) {
694     // Figure out which block (then or else) is executed.
695     const Stmt *Executed = S.getThen();
696     const Stmt *Skipped  = S.getElse();
697     if (!CondConstant)  // Condition false?
698       std::swap(Executed, Skipped);
699 
700     // If the skipped block has no labels in it, just emit the executed block.
701     // This avoids emitting dead code and simplifies the CFG substantially.
702     if (S.isConstexpr() || !ContainsLabel(Skipped)) {
703       if (CondConstant)
704         incrementProfileCounter(&S);
705       if (Executed) {
706         RunCleanupsScope ExecutedScope(*this);
707         EmitStmt(Executed);
708       }
709       return;
710     }
711   }
712 
713   // Otherwise, the condition did not fold, or we couldn't elide it.  Just emit
714   // the conditional branch.
715   llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
716   llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
717   llvm::BasicBlock *ElseBlock = ContBlock;
718   if (S.getElse())
719     ElseBlock = createBasicBlock("if.else");
720 
721   // Prefer the PGO based weights over the likelihood attribute.
722   // When the build isn't optimized the metadata isn't used, so don't generate
723   // it.
724   Stmt::Likelihood LH = Stmt::LH_None;
725   uint64_t Count = getProfileCount(S.getThen());
726   if (!Count && CGM.getCodeGenOpts().OptimizationLevel)
727     LH = Stmt::getLikelihood(S.getThen(), S.getElse());
728   EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock, Count, LH);
729 
730   // Emit the 'then' code.
731   EmitBlock(ThenBlock);
732   incrementProfileCounter(&S);
733   {
734     RunCleanupsScope ThenScope(*this);
735     EmitStmt(S.getThen());
736   }
737   EmitBranch(ContBlock);
738 
739   // Emit the 'else' code if present.
740   if (const Stmt *Else = S.getElse()) {
741     {
742       // There is no need to emit line number for an unconditional branch.
743       auto NL = ApplyDebugLocation::CreateEmpty(*this);
744       EmitBlock(ElseBlock);
745     }
746     {
747       RunCleanupsScope ElseScope(*this);
748       EmitStmt(Else);
749     }
750     {
751       // There is no need to emit line number for an unconditional branch.
752       auto NL = ApplyDebugLocation::CreateEmpty(*this);
753       EmitBranch(ContBlock);
754     }
755   }
756 
757   // Emit the continuation block for code after the if.
758   EmitBlock(ContBlock, true);
759 }
760 
761 void CodeGenFunction::EmitWhileStmt(const WhileStmt &S,
762                                     ArrayRef<const Attr *> WhileAttrs) {
763   // Emit the header for the loop, which will also become
764   // the continue target.
765   JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
766   EmitBlock(LoopHeader.getBlock());
767 
768   const SourceRange &R = S.getSourceRange();
769   LoopStack.push(LoopHeader.getBlock(), CGM.getContext(), CGM.getCodeGenOpts(),
770                  WhileAttrs, SourceLocToDebugLoc(R.getBegin()),
771                  SourceLocToDebugLoc(R.getEnd()));
772 
773   // Create an exit block for when the condition fails, which will
774   // also become the break target.
775   JumpDest LoopExit = getJumpDestInCurrentScope("while.end");
776 
777   // Store the blocks to use for break and continue.
778   BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader));
779 
780   // C++ [stmt.while]p2:
781   //   When the condition of a while statement is a declaration, the
782   //   scope of the variable that is declared extends from its point
783   //   of declaration (3.3.2) to the end of the while statement.
784   //   [...]
785   //   The object created in a condition is destroyed and created
786   //   with each iteration of the loop.
787   RunCleanupsScope ConditionScope(*this);
788 
789   if (S.getConditionVariable())
790     EmitDecl(*S.getConditionVariable());
791 
792   // Evaluate the conditional in the while header.  C99 6.8.5.1: The
793   // evaluation of the controlling expression takes place before each
794   // execution of the loop body.
795   llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
796 
797   // while(1) is common, avoid extra exit blocks.  Be sure
798   // to correctly handle break/continue though.
799   bool EmitBoolCondBranch = true;
800   if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
801     if (C->isOne())
802       EmitBoolCondBranch = false;
803 
804   // As long as the condition is true, go to the loop body.
805   llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
806   if (EmitBoolCondBranch) {
807     llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
808     if (ConditionScope.requiresCleanups())
809       ExitBlock = createBasicBlock("while.exit");
810     llvm::MDNode *Weights = createProfileOrBranchWeightsForLoop(
811         S.getCond(), getProfileCount(S.getBody()), S.getBody());
812     Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock, Weights);
813 
814     if (ExitBlock != LoopExit.getBlock()) {
815       EmitBlock(ExitBlock);
816       EmitBranchThroughCleanup(LoopExit);
817     }
818   } else if (const Attr *A = Stmt::getLikelihoodAttr(S.getBody())) {
819     CGM.getDiags().Report(A->getLocation(),
820                           diag::warn_attribute_has_no_effect_on_infinite_loop)
821         << A << A->getRange();
822     CGM.getDiags().Report(
823         S.getWhileLoc(),
824         diag::note_attribute_has_no_effect_on_infinite_loop_here)
825         << SourceRange(S.getWhileLoc(), S.getRParenLoc());
826   }
827 
828   // Emit the loop body.  We have to emit this in a cleanup scope
829   // because it might be a singleton DeclStmt.
830   {
831     RunCleanupsScope BodyScope(*this);
832     EmitBlock(LoopBody);
833     incrementProfileCounter(&S);
834     EmitStmt(S.getBody());
835   }
836 
837   BreakContinueStack.pop_back();
838 
839   // Immediately force cleanup.
840   ConditionScope.ForceCleanup();
841 
842   EmitStopPoint(&S);
843   // Branch to the loop header again.
844   EmitBranch(LoopHeader.getBlock());
845 
846   LoopStack.pop();
847 
848   // Emit the exit block.
849   EmitBlock(LoopExit.getBlock(), true);
850 
851   // The LoopHeader typically is just a branch if we skipped emitting
852   // a branch, try to erase it.
853   if (!EmitBoolCondBranch)
854     SimplifyForwardingBlocks(LoopHeader.getBlock());
855 }
856 
857 void CodeGenFunction::EmitDoStmt(const DoStmt &S,
858                                  ArrayRef<const Attr *> DoAttrs) {
859   JumpDest LoopExit = getJumpDestInCurrentScope("do.end");
860   JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
861 
862   uint64_t ParentCount = getCurrentProfileCount();
863 
864   // Store the blocks to use for break and continue.
865   BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond));
866 
867   // Emit the body of the loop.
868   llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
869 
870   EmitBlockWithFallThrough(LoopBody, &S);
871   {
872     RunCleanupsScope BodyScope(*this);
873     EmitStmt(S.getBody());
874   }
875 
876   EmitBlock(LoopCond.getBlock());
877 
878   const SourceRange &R = S.getSourceRange();
879   LoopStack.push(LoopBody, CGM.getContext(), CGM.getCodeGenOpts(), DoAttrs,
880                  SourceLocToDebugLoc(R.getBegin()),
881                  SourceLocToDebugLoc(R.getEnd()));
882 
883   // C99 6.8.5.2: "The evaluation of the controlling expression takes place
884   // after each execution of the loop body."
885 
886   // Evaluate the conditional in the while header.
887   // C99 6.8.5p2/p4: The first substatement is executed if the expression
888   // compares unequal to 0.  The condition must be a scalar type.
889   llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
890 
891   BreakContinueStack.pop_back();
892 
893   // "do {} while (0)" is common in macros, avoid extra blocks.  Be sure
894   // to correctly handle break/continue though.
895   bool EmitBoolCondBranch = true;
896   if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
897     if (C->isZero())
898       EmitBoolCondBranch = false;
899 
900   // As long as the condition is true, iterate the loop.
901   if (EmitBoolCondBranch) {
902     uint64_t BackedgeCount = getProfileCount(S.getBody()) - ParentCount;
903     Builder.CreateCondBr(
904         BoolCondVal, LoopBody, LoopExit.getBlock(),
905         createProfileWeightsForLoop(S.getCond(), BackedgeCount));
906   }
907 
908   LoopStack.pop();
909 
910   // Emit the exit block.
911   EmitBlock(LoopExit.getBlock());
912 
913   // The DoCond block typically is just a branch if we skipped
914   // emitting a branch, try to erase it.
915   if (!EmitBoolCondBranch)
916     SimplifyForwardingBlocks(LoopCond.getBlock());
917 }
918 
919 void CodeGenFunction::EmitForStmt(const ForStmt &S,
920                                   ArrayRef<const Attr *> ForAttrs) {
921   JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
922 
923   LexicalScope ForScope(*this, S.getSourceRange());
924 
925   // Evaluate the first part before the loop.
926   if (S.getInit())
927     EmitStmt(S.getInit());
928 
929   // Start the loop with a block that tests the condition.
930   // If there's an increment, the continue scope will be overwritten
931   // later.
932   JumpDest Continue = getJumpDestInCurrentScope("for.cond");
933   llvm::BasicBlock *CondBlock = Continue.getBlock();
934   EmitBlock(CondBlock);
935 
936   const SourceRange &R = S.getSourceRange();
937   LoopStack.push(CondBlock, CGM.getContext(), CGM.getCodeGenOpts(), ForAttrs,
938                  SourceLocToDebugLoc(R.getBegin()),
939                  SourceLocToDebugLoc(R.getEnd()));
940 
941   // If the for loop doesn't have an increment we can just use the
942   // condition as the continue block.  Otherwise we'll need to create
943   // a block for it (in the current scope, i.e. in the scope of the
944   // condition), and that we will become our continue block.
945   if (S.getInc())
946     Continue = getJumpDestInCurrentScope("for.inc");
947 
948   // Store the blocks to use for break and continue.
949   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
950 
951   // Create a cleanup scope for the condition variable cleanups.
952   LexicalScope ConditionScope(*this, S.getSourceRange());
953 
954   if (S.getCond()) {
955     // If the for statement has a condition scope, emit the local variable
956     // declaration.
957     if (S.getConditionVariable()) {
958       EmitDecl(*S.getConditionVariable());
959     }
960 
961     llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
962     // If there are any cleanups between here and the loop-exit scope,
963     // create a block to stage a loop exit along.
964     if (ForScope.requiresCleanups())
965       ExitBlock = createBasicBlock("for.cond.cleanup");
966 
967     // As long as the condition is true, iterate the loop.
968     llvm::BasicBlock *ForBody = createBasicBlock("for.body");
969 
970     // C99 6.8.5p2/p4: The first substatement is executed if the expression
971     // compares unequal to 0.  The condition must be a scalar type.
972     llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
973     llvm::MDNode *Weights = createProfileOrBranchWeightsForLoop(
974         S.getCond(), getProfileCount(S.getBody()), S.getBody());
975     Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock, Weights);
976 
977     if (ExitBlock != LoopExit.getBlock()) {
978       EmitBlock(ExitBlock);
979       EmitBranchThroughCleanup(LoopExit);
980     }
981 
982     EmitBlock(ForBody);
983   } else {
984     // Treat it as a non-zero constant.  Don't even create a new block for the
985     // body, just fall into it.
986   }
987   incrementProfileCounter(&S);
988 
989   {
990     // Create a separate cleanup scope for the body, in case it is not
991     // a compound statement.
992     RunCleanupsScope BodyScope(*this);
993     EmitStmt(S.getBody());
994   }
995 
996   // If there is an increment, emit it next.
997   if (S.getInc()) {
998     EmitBlock(Continue.getBlock());
999     EmitStmt(S.getInc());
1000   }
1001 
1002   BreakContinueStack.pop_back();
1003 
1004   ConditionScope.ForceCleanup();
1005 
1006   EmitStopPoint(&S);
1007   EmitBranch(CondBlock);
1008 
1009   ForScope.ForceCleanup();
1010 
1011   LoopStack.pop();
1012 
1013   // Emit the fall-through block.
1014   EmitBlock(LoopExit.getBlock(), true);
1015 }
1016 
1017 void
1018 CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S,
1019                                      ArrayRef<const Attr *> ForAttrs) {
1020   JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
1021 
1022   LexicalScope ForScope(*this, S.getSourceRange());
1023 
1024   // Evaluate the first pieces before the loop.
1025   if (S.getInit())
1026     EmitStmt(S.getInit());
1027   EmitStmt(S.getRangeStmt());
1028   EmitStmt(S.getBeginStmt());
1029   EmitStmt(S.getEndStmt());
1030 
1031   // Start the loop with a block that tests the condition.
1032   // If there's an increment, the continue scope will be overwritten
1033   // later.
1034   llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1035   EmitBlock(CondBlock);
1036 
1037   const SourceRange &R = S.getSourceRange();
1038   LoopStack.push(CondBlock, CGM.getContext(), CGM.getCodeGenOpts(), ForAttrs,
1039                  SourceLocToDebugLoc(R.getBegin()),
1040                  SourceLocToDebugLoc(R.getEnd()));
1041 
1042   // If there are any cleanups between here and the loop-exit scope,
1043   // create a block to stage a loop exit along.
1044   llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
1045   if (ForScope.requiresCleanups())
1046     ExitBlock = createBasicBlock("for.cond.cleanup");
1047 
1048   // The loop body, consisting of the specified body and the loop variable.
1049   llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1050 
1051   // The body is executed if the expression, contextually converted
1052   // to bool, is true.
1053   llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
1054   llvm::MDNode *Weights = createProfileOrBranchWeightsForLoop(
1055       S.getCond(), getProfileCount(S.getBody()), S.getBody());
1056   Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock, Weights);
1057 
1058   if (ExitBlock != LoopExit.getBlock()) {
1059     EmitBlock(ExitBlock);
1060     EmitBranchThroughCleanup(LoopExit);
1061   }
1062 
1063   EmitBlock(ForBody);
1064   incrementProfileCounter(&S);
1065 
1066   // Create a block for the increment. In case of a 'continue', we jump there.
1067   JumpDest Continue = getJumpDestInCurrentScope("for.inc");
1068 
1069   // Store the blocks to use for break and continue.
1070   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1071 
1072   {
1073     // Create a separate cleanup scope for the loop variable and body.
1074     LexicalScope BodyScope(*this, S.getSourceRange());
1075     EmitStmt(S.getLoopVarStmt());
1076     EmitStmt(S.getBody());
1077   }
1078 
1079   EmitStopPoint(&S);
1080   // If there is an increment, emit it next.
1081   EmitBlock(Continue.getBlock());
1082   EmitStmt(S.getInc());
1083 
1084   BreakContinueStack.pop_back();
1085 
1086   EmitBranch(CondBlock);
1087 
1088   ForScope.ForceCleanup();
1089 
1090   LoopStack.pop();
1091 
1092   // Emit the fall-through block.
1093   EmitBlock(LoopExit.getBlock(), true);
1094 }
1095 
1096 void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
1097   if (RV.isScalar()) {
1098     Builder.CreateStore(RV.getScalarVal(), ReturnValue);
1099   } else if (RV.isAggregate()) {
1100     LValue Dest = MakeAddrLValue(ReturnValue, Ty);
1101     LValue Src = MakeAddrLValue(RV.getAggregateAddress(), Ty);
1102     EmitAggregateCopy(Dest, Src, Ty, getOverlapForReturnValue());
1103   } else {
1104     EmitStoreOfComplex(RV.getComplexVal(), MakeAddrLValue(ReturnValue, Ty),
1105                        /*init*/ true);
1106   }
1107   EmitBranchThroughCleanup(ReturnBlock);
1108 }
1109 
1110 namespace {
1111 // RAII struct used to save and restore a return statment's result expression.
1112 struct SaveRetExprRAII {
1113   SaveRetExprRAII(const Expr *RetExpr, CodeGenFunction &CGF)
1114       : OldRetExpr(CGF.RetExpr), CGF(CGF) {
1115     CGF.RetExpr = RetExpr;
1116   }
1117   ~SaveRetExprRAII() { CGF.RetExpr = OldRetExpr; }
1118   const Expr *OldRetExpr;
1119   CodeGenFunction &CGF;
1120 };
1121 } // namespace
1122 
1123 /// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
1124 /// if the function returns void, or may be missing one if the function returns
1125 /// non-void.  Fun stuff :).
1126 void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
1127   if (requiresReturnValueCheck()) {
1128     llvm::Constant *SLoc = EmitCheckSourceLocation(S.getBeginLoc());
1129     auto *SLocPtr =
1130         new llvm::GlobalVariable(CGM.getModule(), SLoc->getType(), false,
1131                                  llvm::GlobalVariable::PrivateLinkage, SLoc);
1132     SLocPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1133     CGM.getSanitizerMetadata()->disableSanitizerForGlobal(SLocPtr);
1134     assert(ReturnLocation.isValid() && "No valid return location");
1135     Builder.CreateStore(Builder.CreateBitCast(SLocPtr, Int8PtrTy),
1136                         ReturnLocation);
1137   }
1138 
1139   // Returning from an outlined SEH helper is UB, and we already warn on it.
1140   if (IsOutlinedSEHHelper) {
1141     Builder.CreateUnreachable();
1142     Builder.ClearInsertionPoint();
1143   }
1144 
1145   // Emit the result value, even if unused, to evaluate the side effects.
1146   const Expr *RV = S.getRetValue();
1147 
1148   // Record the result expression of the return statement. The recorded
1149   // expression is used to determine whether a block capture's lifetime should
1150   // end at the end of the full expression as opposed to the end of the scope
1151   // enclosing the block expression.
1152   //
1153   // This permits a small, easily-implemented exception to our over-conservative
1154   // rules about not jumping to statements following block literals with
1155   // non-trivial cleanups.
1156   SaveRetExprRAII SaveRetExpr(RV, *this);
1157 
1158   RunCleanupsScope cleanupScope(*this);
1159   if (const auto *EWC = dyn_cast_or_null<ExprWithCleanups>(RV))
1160     RV = EWC->getSubExpr();
1161   // FIXME: Clean this up by using an LValue for ReturnTemp,
1162   // EmitStoreThroughLValue, and EmitAnyExpr.
1163   // Check if the NRVO candidate was not globalized in OpenMP mode.
1164   if (getLangOpts().ElideConstructors && S.getNRVOCandidate() &&
1165       S.getNRVOCandidate()->isNRVOVariable() &&
1166       (!getLangOpts().OpenMP ||
1167        !CGM.getOpenMPRuntime()
1168             .getAddressOfLocalVariable(*this, S.getNRVOCandidate())
1169             .isValid())) {
1170     // Apply the named return value optimization for this return statement,
1171     // which means doing nothing: the appropriate result has already been
1172     // constructed into the NRVO variable.
1173 
1174     // If there is an NRVO flag for this variable, set it to 1 into indicate
1175     // that the cleanup code should not destroy the variable.
1176     if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
1177       Builder.CreateFlagStore(Builder.getTrue(), NRVOFlag);
1178   } else if (!ReturnValue.isValid() || (RV && RV->getType()->isVoidType())) {
1179     // Make sure not to return anything, but evaluate the expression
1180     // for side effects.
1181     if (RV)
1182       EmitAnyExpr(RV);
1183   } else if (!RV) {
1184     // Do nothing (return value is left uninitialized)
1185   } else if (FnRetTy->isReferenceType()) {
1186     // If this function returns a reference, take the address of the expression
1187     // rather than the value.
1188     RValue Result = EmitReferenceBindingToExpr(RV);
1189     Builder.CreateStore(Result.getScalarVal(), ReturnValue);
1190   } else {
1191     switch (getEvaluationKind(RV->getType())) {
1192     case TEK_Scalar:
1193       Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
1194       break;
1195     case TEK_Complex:
1196       EmitComplexExprIntoLValue(RV, MakeAddrLValue(ReturnValue, RV->getType()),
1197                                 /*isInit*/ true);
1198       break;
1199     case TEK_Aggregate:
1200       EmitAggExpr(RV, AggValueSlot::forAddr(
1201                           ReturnValue, Qualifiers(),
1202                           AggValueSlot::IsDestructed,
1203                           AggValueSlot::DoesNotNeedGCBarriers,
1204                           AggValueSlot::IsNotAliased,
1205                           getOverlapForReturnValue()));
1206       break;
1207     }
1208   }
1209 
1210   ++NumReturnExprs;
1211   if (!RV || RV->isEvaluatable(getContext()))
1212     ++NumSimpleReturnExprs;
1213 
1214   cleanupScope.ForceCleanup();
1215   EmitBranchThroughCleanup(ReturnBlock);
1216 }
1217 
1218 void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
1219   // As long as debug info is modeled with instructions, we have to ensure we
1220   // have a place to insert here and write the stop point here.
1221   if (HaveInsertPoint())
1222     EmitStopPoint(&S);
1223 
1224   for (const auto *I : S.decls())
1225     EmitDecl(*I);
1226 }
1227 
1228 void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
1229   assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
1230 
1231   // If this code is reachable then emit a stop point (if generating
1232   // debug info). We have to do this ourselves because we are on the
1233   // "simple" statement path.
1234   if (HaveInsertPoint())
1235     EmitStopPoint(&S);
1236 
1237   EmitBranchThroughCleanup(BreakContinueStack.back().BreakBlock);
1238 }
1239 
1240 void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
1241   assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
1242 
1243   // If this code is reachable then emit a stop point (if generating
1244   // debug info). We have to do this ourselves because we are on the
1245   // "simple" statement path.
1246   if (HaveInsertPoint())
1247     EmitStopPoint(&S);
1248 
1249   EmitBranchThroughCleanup(BreakContinueStack.back().ContinueBlock);
1250 }
1251 
1252 /// EmitCaseStmtRange - If case statement range is not too big then
1253 /// add multiple cases to switch instruction, one for each value within
1254 /// the range. If range is too big then emit "if" condition check.
1255 void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S,
1256                                         ArrayRef<const Attr *> Attrs) {
1257   assert(S.getRHS() && "Expected RHS value in CaseStmt");
1258 
1259   llvm::APSInt LHS = S.getLHS()->EvaluateKnownConstInt(getContext());
1260   llvm::APSInt RHS = S.getRHS()->EvaluateKnownConstInt(getContext());
1261 
1262   // Emit the code for this case. We do this first to make sure it is
1263   // properly chained from our predecessor before generating the
1264   // switch machinery to enter this block.
1265   llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
1266   EmitBlockWithFallThrough(CaseDest, &S);
1267   EmitStmt(S.getSubStmt());
1268 
1269   // If range is empty, do nothing.
1270   if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
1271     return;
1272 
1273   Stmt::Likelihood LH = Stmt::getLikelihood(Attrs);
1274   llvm::APInt Range = RHS - LHS;
1275   // FIXME: parameters such as this should not be hardcoded.
1276   if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
1277     // Range is small enough to add multiple switch instruction cases.
1278     uint64_t Total = getProfileCount(&S);
1279     unsigned NCases = Range.getZExtValue() + 1;
1280     // We only have one region counter for the entire set of cases here, so we
1281     // need to divide the weights evenly between the generated cases, ensuring
1282     // that the total weight is preserved. E.g., a weight of 5 over three cases
1283     // will be distributed as weights of 2, 2, and 1.
1284     uint64_t Weight = Total / NCases, Rem = Total % NCases;
1285     for (unsigned I = 0; I != NCases; ++I) {
1286       if (SwitchWeights)
1287         SwitchWeights->push_back(Weight + (Rem ? 1 : 0));
1288       else if (SwitchLikelihood)
1289         SwitchLikelihood->push_back(LH);
1290 
1291       if (Rem)
1292         Rem--;
1293       SwitchInsn->addCase(Builder.getInt(LHS), CaseDest);
1294       ++LHS;
1295     }
1296     return;
1297   }
1298 
1299   // The range is too big. Emit "if" condition into a new block,
1300   // making sure to save and restore the current insertion point.
1301   llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
1302 
1303   // Push this test onto the chain of range checks (which terminates
1304   // in the default basic block). The switch's default will be changed
1305   // to the top of this chain after switch emission is complete.
1306   llvm::BasicBlock *FalseDest = CaseRangeBlock;
1307   CaseRangeBlock = createBasicBlock("sw.caserange");
1308 
1309   CurFn->getBasicBlockList().push_back(CaseRangeBlock);
1310   Builder.SetInsertPoint(CaseRangeBlock);
1311 
1312   // Emit range check.
1313   llvm::Value *Diff =
1314     Builder.CreateSub(SwitchInsn->getCondition(), Builder.getInt(LHS));
1315   llvm::Value *Cond =
1316     Builder.CreateICmpULE(Diff, Builder.getInt(Range), "inbounds");
1317 
1318   llvm::MDNode *Weights = nullptr;
1319   if (SwitchWeights) {
1320     uint64_t ThisCount = getProfileCount(&S);
1321     uint64_t DefaultCount = (*SwitchWeights)[0];
1322     Weights = createProfileWeights(ThisCount, DefaultCount);
1323 
1324     // Since we're chaining the switch default through each large case range, we
1325     // need to update the weight for the default, ie, the first case, to include
1326     // this case.
1327     (*SwitchWeights)[0] += ThisCount;
1328   } else if (SwitchLikelihood)
1329     Weights = createBranchWeights(LH);
1330 
1331   Builder.CreateCondBr(Cond, CaseDest, FalseDest, Weights);
1332 
1333   // Restore the appropriate insertion point.
1334   if (RestoreBB)
1335     Builder.SetInsertPoint(RestoreBB);
1336   else
1337     Builder.ClearInsertionPoint();
1338 }
1339 
1340 void CodeGenFunction::EmitCaseStmt(const CaseStmt &S,
1341                                    ArrayRef<const Attr *> Attrs) {
1342   // If there is no enclosing switch instance that we're aware of, then this
1343   // case statement and its block can be elided.  This situation only happens
1344   // when we've constant-folded the switch, are emitting the constant case,
1345   // and part of the constant case includes another case statement.  For
1346   // instance: switch (4) { case 4: do { case 5: } while (1); }
1347   if (!SwitchInsn) {
1348     EmitStmt(S.getSubStmt());
1349     return;
1350   }
1351 
1352   // Handle case ranges.
1353   if (S.getRHS()) {
1354     EmitCaseStmtRange(S, Attrs);
1355     return;
1356   }
1357 
1358   llvm::ConstantInt *CaseVal =
1359     Builder.getInt(S.getLHS()->EvaluateKnownConstInt(getContext()));
1360   if (SwitchLikelihood)
1361     SwitchLikelihood->push_back(Stmt::getLikelihood(Attrs));
1362 
1363   // If the body of the case is just a 'break', try to not emit an empty block.
1364   // If we're profiling or we're not optimizing, leave the block in for better
1365   // debug and coverage analysis.
1366   if (!CGM.getCodeGenOpts().hasProfileClangInstr() &&
1367       CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1368       isa<BreakStmt>(S.getSubStmt())) {
1369     JumpDest Block = BreakContinueStack.back().BreakBlock;
1370 
1371     // Only do this optimization if there are no cleanups that need emitting.
1372     if (isObviouslyBranchWithoutCleanups(Block)) {
1373       if (SwitchWeights)
1374         SwitchWeights->push_back(getProfileCount(&S));
1375       SwitchInsn->addCase(CaseVal, Block.getBlock());
1376 
1377       // If there was a fallthrough into this case, make sure to redirect it to
1378       // the end of the switch as well.
1379       if (Builder.GetInsertBlock()) {
1380         Builder.CreateBr(Block.getBlock());
1381         Builder.ClearInsertionPoint();
1382       }
1383       return;
1384     }
1385   }
1386 
1387   llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
1388   EmitBlockWithFallThrough(CaseDest, &S);
1389   if (SwitchWeights)
1390     SwitchWeights->push_back(getProfileCount(&S));
1391   SwitchInsn->addCase(CaseVal, CaseDest);
1392 
1393   // Recursively emitting the statement is acceptable, but is not wonderful for
1394   // code where we have many case statements nested together, i.e.:
1395   //  case 1:
1396   //    case 2:
1397   //      case 3: etc.
1398   // Handling this recursively will create a new block for each case statement
1399   // that falls through to the next case which is IR intensive.  It also causes
1400   // deep recursion which can run into stack depth limitations.  Handle
1401   // sequential non-range case statements specially.
1402   //
1403   // TODO When the next case has a likelihood attribute the code returns to the
1404   // recursive algorithm. Maybe improve this case if it becomes common practice
1405   // to use a lot of attributes.
1406   const CaseStmt *CurCase = &S;
1407   const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
1408 
1409   // Otherwise, iteratively add consecutive cases to this switch stmt.
1410   while (NextCase && NextCase->getRHS() == nullptr) {
1411     CurCase = NextCase;
1412     llvm::ConstantInt *CaseVal =
1413       Builder.getInt(CurCase->getLHS()->EvaluateKnownConstInt(getContext()));
1414 
1415     if (SwitchWeights)
1416       SwitchWeights->push_back(getProfileCount(NextCase));
1417     if (CGM.getCodeGenOpts().hasProfileClangInstr()) {
1418       CaseDest = createBasicBlock("sw.bb");
1419       EmitBlockWithFallThrough(CaseDest, &S);
1420     }
1421     // Since this loop is only executed when the CaseStmt has no attributes
1422     // use a hard-coded value.
1423     if (SwitchLikelihood)
1424       SwitchLikelihood->push_back(Stmt::LH_None);
1425 
1426     SwitchInsn->addCase(CaseVal, CaseDest);
1427     NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
1428   }
1429 
1430   // Normal default recursion for non-cases.
1431   EmitStmt(CurCase->getSubStmt());
1432 }
1433 
1434 void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S,
1435                                       ArrayRef<const Attr *> Attrs) {
1436   // If there is no enclosing switch instance that we're aware of, then this
1437   // default statement can be elided. This situation only happens when we've
1438   // constant-folded the switch.
1439   if (!SwitchInsn) {
1440     EmitStmt(S.getSubStmt());
1441     return;
1442   }
1443 
1444   llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
1445   assert(DefaultBlock->empty() &&
1446          "EmitDefaultStmt: Default block already defined?");
1447 
1448   if (SwitchLikelihood)
1449     SwitchLikelihood->front() = Stmt::getLikelihood(Attrs);
1450 
1451   EmitBlockWithFallThrough(DefaultBlock, &S);
1452 
1453   EmitStmt(S.getSubStmt());
1454 }
1455 
1456 /// CollectStatementsForCase - Given the body of a 'switch' statement and a
1457 /// constant value that is being switched on, see if we can dead code eliminate
1458 /// the body of the switch to a simple series of statements to emit.  Basically,
1459 /// on a switch (5) we want to find these statements:
1460 ///    case 5:
1461 ///      printf(...);    <--
1462 ///      ++i;            <--
1463 ///      break;
1464 ///
1465 /// and add them to the ResultStmts vector.  If it is unsafe to do this
1466 /// transformation (for example, one of the elided statements contains a label
1467 /// that might be jumped to), return CSFC_Failure.  If we handled it and 'S'
1468 /// should include statements after it (e.g. the printf() line is a substmt of
1469 /// the case) then return CSFC_FallThrough.  If we handled it and found a break
1470 /// statement, then return CSFC_Success.
1471 ///
1472 /// If Case is non-null, then we are looking for the specified case, checking
1473 /// that nothing we jump over contains labels.  If Case is null, then we found
1474 /// the case and are looking for the break.
1475 ///
1476 /// If the recursive walk actually finds our Case, then we set FoundCase to
1477 /// true.
1478 ///
1479 enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success };
1480 static CSFC_Result CollectStatementsForCase(const Stmt *S,
1481                                             const SwitchCase *Case,
1482                                             bool &FoundCase,
1483                               SmallVectorImpl<const Stmt*> &ResultStmts) {
1484   // If this is a null statement, just succeed.
1485   if (!S)
1486     return Case ? CSFC_Success : CSFC_FallThrough;
1487 
1488   // If this is the switchcase (case 4: or default) that we're looking for, then
1489   // we're in business.  Just add the substatement.
1490   if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) {
1491     if (S == Case) {
1492       FoundCase = true;
1493       return CollectStatementsForCase(SC->getSubStmt(), nullptr, FoundCase,
1494                                       ResultStmts);
1495     }
1496 
1497     // Otherwise, this is some other case or default statement, just ignore it.
1498     return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase,
1499                                     ResultStmts);
1500   }
1501 
1502   // If we are in the live part of the code and we found our break statement,
1503   // return a success!
1504   if (!Case && isa<BreakStmt>(S))
1505     return CSFC_Success;
1506 
1507   // If this is a switch statement, then it might contain the SwitchCase, the
1508   // break, or neither.
1509   if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
1510     // Handle this as two cases: we might be looking for the SwitchCase (if so
1511     // the skipped statements must be skippable) or we might already have it.
1512     CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end();
1513     bool StartedInLiveCode = FoundCase;
1514     unsigned StartSize = ResultStmts.size();
1515 
1516     // If we've not found the case yet, scan through looking for it.
1517     if (Case) {
1518       // Keep track of whether we see a skipped declaration.  The code could be
1519       // using the declaration even if it is skipped, so we can't optimize out
1520       // the decl if the kept statements might refer to it.
1521       bool HadSkippedDecl = false;
1522 
1523       // If we're looking for the case, just see if we can skip each of the
1524       // substatements.
1525       for (; Case && I != E; ++I) {
1526         HadSkippedDecl |= CodeGenFunction::mightAddDeclToScope(*I);
1527 
1528         switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) {
1529         case CSFC_Failure: return CSFC_Failure;
1530         case CSFC_Success:
1531           // A successful result means that either 1) that the statement doesn't
1532           // have the case and is skippable, or 2) does contain the case value
1533           // and also contains the break to exit the switch.  In the later case,
1534           // we just verify the rest of the statements are elidable.
1535           if (FoundCase) {
1536             // If we found the case and skipped declarations, we can't do the
1537             // optimization.
1538             if (HadSkippedDecl)
1539               return CSFC_Failure;
1540 
1541             for (++I; I != E; ++I)
1542               if (CodeGenFunction::ContainsLabel(*I, true))
1543                 return CSFC_Failure;
1544             return CSFC_Success;
1545           }
1546           break;
1547         case CSFC_FallThrough:
1548           // If we have a fallthrough condition, then we must have found the
1549           // case started to include statements.  Consider the rest of the
1550           // statements in the compound statement as candidates for inclusion.
1551           assert(FoundCase && "Didn't find case but returned fallthrough?");
1552           // We recursively found Case, so we're not looking for it anymore.
1553           Case = nullptr;
1554 
1555           // If we found the case and skipped declarations, we can't do the
1556           // optimization.
1557           if (HadSkippedDecl)
1558             return CSFC_Failure;
1559           break;
1560         }
1561       }
1562 
1563       if (!FoundCase)
1564         return CSFC_Success;
1565 
1566       assert(!HadSkippedDecl && "fallthrough after skipping decl");
1567     }
1568 
1569     // If we have statements in our range, then we know that the statements are
1570     // live and need to be added to the set of statements we're tracking.
1571     bool AnyDecls = false;
1572     for (; I != E; ++I) {
1573       AnyDecls |= CodeGenFunction::mightAddDeclToScope(*I);
1574 
1575       switch (CollectStatementsForCase(*I, nullptr, FoundCase, ResultStmts)) {
1576       case CSFC_Failure: return CSFC_Failure;
1577       case CSFC_FallThrough:
1578         // A fallthrough result means that the statement was simple and just
1579         // included in ResultStmt, keep adding them afterwards.
1580         break;
1581       case CSFC_Success:
1582         // A successful result means that we found the break statement and
1583         // stopped statement inclusion.  We just ensure that any leftover stmts
1584         // are skippable and return success ourselves.
1585         for (++I; I != E; ++I)
1586           if (CodeGenFunction::ContainsLabel(*I, true))
1587             return CSFC_Failure;
1588         return CSFC_Success;
1589       }
1590     }
1591 
1592     // If we're about to fall out of a scope without hitting a 'break;', we
1593     // can't perform the optimization if there were any decls in that scope
1594     // (we'd lose their end-of-lifetime).
1595     if (AnyDecls) {
1596       // If the entire compound statement was live, there's one more thing we
1597       // can try before giving up: emit the whole thing as a single statement.
1598       // We can do that unless the statement contains a 'break;'.
1599       // FIXME: Such a break must be at the end of a construct within this one.
1600       // We could emit this by just ignoring the BreakStmts entirely.
1601       if (StartedInLiveCode && !CodeGenFunction::containsBreak(S)) {
1602         ResultStmts.resize(StartSize);
1603         ResultStmts.push_back(S);
1604       } else {
1605         return CSFC_Failure;
1606       }
1607     }
1608 
1609     return CSFC_FallThrough;
1610   }
1611 
1612   // Okay, this is some other statement that we don't handle explicitly, like a
1613   // for statement or increment etc.  If we are skipping over this statement,
1614   // just verify it doesn't have labels, which would make it invalid to elide.
1615   if (Case) {
1616     if (CodeGenFunction::ContainsLabel(S, true))
1617       return CSFC_Failure;
1618     return CSFC_Success;
1619   }
1620 
1621   // Otherwise, we want to include this statement.  Everything is cool with that
1622   // so long as it doesn't contain a break out of the switch we're in.
1623   if (CodeGenFunction::containsBreak(S)) return CSFC_Failure;
1624 
1625   // Otherwise, everything is great.  Include the statement and tell the caller
1626   // that we fall through and include the next statement as well.
1627   ResultStmts.push_back(S);
1628   return CSFC_FallThrough;
1629 }
1630 
1631 /// FindCaseStatementsForValue - Find the case statement being jumped to and
1632 /// then invoke CollectStatementsForCase to find the list of statements to emit
1633 /// for a switch on constant.  See the comment above CollectStatementsForCase
1634 /// for more details.
1635 static bool FindCaseStatementsForValue(const SwitchStmt &S,
1636                                        const llvm::APSInt &ConstantCondValue,
1637                                 SmallVectorImpl<const Stmt*> &ResultStmts,
1638                                        ASTContext &C,
1639                                        const SwitchCase *&ResultCase) {
1640   // First step, find the switch case that is being branched to.  We can do this
1641   // efficiently by scanning the SwitchCase list.
1642   const SwitchCase *Case = S.getSwitchCaseList();
1643   const DefaultStmt *DefaultCase = nullptr;
1644 
1645   for (; Case; Case = Case->getNextSwitchCase()) {
1646     // It's either a default or case.  Just remember the default statement in
1647     // case we're not jumping to any numbered cases.
1648     if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) {
1649       DefaultCase = DS;
1650       continue;
1651     }
1652 
1653     // Check to see if this case is the one we're looking for.
1654     const CaseStmt *CS = cast<CaseStmt>(Case);
1655     // Don't handle case ranges yet.
1656     if (CS->getRHS()) return false;
1657 
1658     // If we found our case, remember it as 'case'.
1659     if (CS->getLHS()->EvaluateKnownConstInt(C) == ConstantCondValue)
1660       break;
1661   }
1662 
1663   // If we didn't find a matching case, we use a default if it exists, or we
1664   // elide the whole switch body!
1665   if (!Case) {
1666     // It is safe to elide the body of the switch if it doesn't contain labels
1667     // etc.  If it is safe, return successfully with an empty ResultStmts list.
1668     if (!DefaultCase)
1669       return !CodeGenFunction::ContainsLabel(&S);
1670     Case = DefaultCase;
1671   }
1672 
1673   // Ok, we know which case is being jumped to, try to collect all the
1674   // statements that follow it.  This can fail for a variety of reasons.  Also,
1675   // check to see that the recursive walk actually found our case statement.
1676   // Insane cases like this can fail to find it in the recursive walk since we
1677   // don't handle every stmt kind:
1678   // switch (4) {
1679   //   while (1) {
1680   //     case 4: ...
1681   bool FoundCase = false;
1682   ResultCase = Case;
1683   return CollectStatementsForCase(S.getBody(), Case, FoundCase,
1684                                   ResultStmts) != CSFC_Failure &&
1685          FoundCase;
1686 }
1687 
1688 static Optional<SmallVector<uint64_t, 16>>
1689 getLikelihoodWeights(ArrayRef<Stmt::Likelihood> Likelihoods) {
1690   // Are there enough branches to weight them?
1691   if (Likelihoods.size() <= 1)
1692     return None;
1693 
1694   uint64_t NumUnlikely = 0;
1695   uint64_t NumNone = 0;
1696   uint64_t NumLikely = 0;
1697   for (const auto LH : Likelihoods) {
1698     switch (LH) {
1699     case Stmt::LH_Unlikely:
1700       ++NumUnlikely;
1701       break;
1702     case Stmt::LH_None:
1703       ++NumNone;
1704       break;
1705     case Stmt::LH_Likely:
1706       ++NumLikely;
1707       break;
1708     }
1709   }
1710 
1711   // Is there a likelihood attribute used?
1712   if (NumUnlikely == 0 && NumLikely == 0)
1713     return None;
1714 
1715   // When multiple cases share the same code they can be combined during
1716   // optimization. In that case the weights of the branch will be the sum of
1717   // the individual weights. Make sure the combined sum of all neutral cases
1718   // doesn't exceed the value of a single likely attribute.
1719   // The additions both avoid divisions by 0 and make sure the weights of None
1720   // don't exceed the weight of Likely.
1721   const uint64_t Likely = INT32_MAX / (NumLikely + 2);
1722   const uint64_t None = Likely / (NumNone + 1);
1723   const uint64_t Unlikely = 0;
1724 
1725   SmallVector<uint64_t, 16> Result;
1726   Result.reserve(Likelihoods.size());
1727   for (const auto LH : Likelihoods) {
1728     switch (LH) {
1729     case Stmt::LH_Unlikely:
1730       Result.push_back(Unlikely);
1731       break;
1732     case Stmt::LH_None:
1733       Result.push_back(None);
1734       break;
1735     case Stmt::LH_Likely:
1736       Result.push_back(Likely);
1737       break;
1738     }
1739   }
1740 
1741   return Result;
1742 }
1743 
1744 void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
1745   // Handle nested switch statements.
1746   llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
1747   SmallVector<uint64_t, 16> *SavedSwitchWeights = SwitchWeights;
1748   SmallVector<Stmt::Likelihood, 16> *SavedSwitchLikelihood = SwitchLikelihood;
1749   llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
1750 
1751   // See if we can constant fold the condition of the switch and therefore only
1752   // emit the live case statement (if any) of the switch.
1753   llvm::APSInt ConstantCondValue;
1754   if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
1755     SmallVector<const Stmt*, 4> CaseStmts;
1756     const SwitchCase *Case = nullptr;
1757     if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,
1758                                    getContext(), Case)) {
1759       if (Case)
1760         incrementProfileCounter(Case);
1761       RunCleanupsScope ExecutedScope(*this);
1762 
1763       if (S.getInit())
1764         EmitStmt(S.getInit());
1765 
1766       // Emit the condition variable if needed inside the entire cleanup scope
1767       // used by this special case for constant folded switches.
1768       if (S.getConditionVariable())
1769         EmitDecl(*S.getConditionVariable());
1770 
1771       // At this point, we are no longer "within" a switch instance, so
1772       // we can temporarily enforce this to ensure that any embedded case
1773       // statements are not emitted.
1774       SwitchInsn = nullptr;
1775 
1776       // Okay, we can dead code eliminate everything except this case.  Emit the
1777       // specified series of statements and we're good.
1778       for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i)
1779         EmitStmt(CaseStmts[i]);
1780       incrementProfileCounter(&S);
1781 
1782       // Now we want to restore the saved switch instance so that nested
1783       // switches continue to function properly
1784       SwitchInsn = SavedSwitchInsn;
1785 
1786       return;
1787     }
1788   }
1789 
1790   JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
1791 
1792   RunCleanupsScope ConditionScope(*this);
1793 
1794   if (S.getInit())
1795     EmitStmt(S.getInit());
1796 
1797   if (S.getConditionVariable())
1798     EmitDecl(*S.getConditionVariable());
1799   llvm::Value *CondV = EmitScalarExpr(S.getCond());
1800 
1801   // Create basic block to hold stuff that comes after switch
1802   // statement. We also need to create a default block now so that
1803   // explicit case ranges tests can have a place to jump to on
1804   // failure.
1805   llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
1806   SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
1807   if (PGO.haveRegionCounts()) {
1808     // Walk the SwitchCase list to find how many there are.
1809     uint64_t DefaultCount = 0;
1810     unsigned NumCases = 0;
1811     for (const SwitchCase *Case = S.getSwitchCaseList();
1812          Case;
1813          Case = Case->getNextSwitchCase()) {
1814       if (isa<DefaultStmt>(Case))
1815         DefaultCount = getProfileCount(Case);
1816       NumCases += 1;
1817     }
1818     SwitchWeights = new SmallVector<uint64_t, 16>();
1819     SwitchWeights->reserve(NumCases);
1820     // The default needs to be first. We store the edge count, so we already
1821     // know the right weight.
1822     SwitchWeights->push_back(DefaultCount);
1823   } else if (CGM.getCodeGenOpts().OptimizationLevel) {
1824     SwitchLikelihood = new SmallVector<Stmt::Likelihood, 16>();
1825     // Initialize the default case.
1826     SwitchLikelihood->push_back(Stmt::LH_None);
1827   }
1828 
1829   CaseRangeBlock = DefaultBlock;
1830 
1831   // Clear the insertion point to indicate we are in unreachable code.
1832   Builder.ClearInsertionPoint();
1833 
1834   // All break statements jump to NextBlock. If BreakContinueStack is non-empty
1835   // then reuse last ContinueBlock.
1836   JumpDest OuterContinue;
1837   if (!BreakContinueStack.empty())
1838     OuterContinue = BreakContinueStack.back().ContinueBlock;
1839 
1840   BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
1841 
1842   // Emit switch body.
1843   EmitStmt(S.getBody());
1844 
1845   BreakContinueStack.pop_back();
1846 
1847   // Update the default block in case explicit case range tests have
1848   // been chained on top.
1849   SwitchInsn->setDefaultDest(CaseRangeBlock);
1850 
1851   // If a default was never emitted:
1852   if (!DefaultBlock->getParent()) {
1853     // If we have cleanups, emit the default block so that there's a
1854     // place to jump through the cleanups from.
1855     if (ConditionScope.requiresCleanups()) {
1856       EmitBlock(DefaultBlock);
1857 
1858     // Otherwise, just forward the default block to the switch end.
1859     } else {
1860       DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
1861       delete DefaultBlock;
1862     }
1863   }
1864 
1865   ConditionScope.ForceCleanup();
1866 
1867   // Emit continuation.
1868   EmitBlock(SwitchExit.getBlock(), true);
1869   incrementProfileCounter(&S);
1870 
1871   // If the switch has a condition wrapped by __builtin_unpredictable,
1872   // create metadata that specifies that the switch is unpredictable.
1873   // Don't bother if not optimizing because that metadata would not be used.
1874   auto *Call = dyn_cast<CallExpr>(S.getCond());
1875   if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
1876     auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
1877     if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
1878       llvm::MDBuilder MDHelper(getLLVMContext());
1879       SwitchInsn->setMetadata(llvm::LLVMContext::MD_unpredictable,
1880                               MDHelper.createUnpredictable());
1881     }
1882   }
1883 
1884   if (SwitchWeights) {
1885     assert(SwitchWeights->size() == 1 + SwitchInsn->getNumCases() &&
1886            "switch weights do not match switch cases");
1887     // If there's only one jump destination there's no sense weighting it.
1888     if (SwitchWeights->size() > 1)
1889       SwitchInsn->setMetadata(llvm::LLVMContext::MD_prof,
1890                               createProfileWeights(*SwitchWeights));
1891     delete SwitchWeights;
1892   } else if (SwitchLikelihood) {
1893     assert(SwitchLikelihood->size() == 1 + SwitchInsn->getNumCases() &&
1894            "switch likelihoods do not match switch cases");
1895     Optional<SmallVector<uint64_t, 16>> LHW =
1896         getLikelihoodWeights(*SwitchLikelihood);
1897     if (LHW) {
1898       llvm::MDBuilder MDHelper(CGM.getLLVMContext());
1899       SwitchInsn->setMetadata(llvm::LLVMContext::MD_prof,
1900                               createProfileWeights(*LHW));
1901     }
1902     delete SwitchLikelihood;
1903   }
1904   SwitchInsn = SavedSwitchInsn;
1905   SwitchWeights = SavedSwitchWeights;
1906   SwitchLikelihood = SavedSwitchLikelihood;
1907   CaseRangeBlock = SavedCRBlock;
1908 }
1909 
1910 static std::string
1911 SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
1912                  SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=nullptr) {
1913   std::string Result;
1914 
1915   while (*Constraint) {
1916     switch (*Constraint) {
1917     default:
1918       Result += Target.convertConstraint(Constraint);
1919       break;
1920     // Ignore these
1921     case '*':
1922     case '?':
1923     case '!':
1924     case '=': // Will see this and the following in mult-alt constraints.
1925     case '+':
1926       break;
1927     case '#': // Ignore the rest of the constraint alternative.
1928       while (Constraint[1] && Constraint[1] != ',')
1929         Constraint++;
1930       break;
1931     case '&':
1932     case '%':
1933       Result += *Constraint;
1934       while (Constraint[1] && Constraint[1] == *Constraint)
1935         Constraint++;
1936       break;
1937     case ',':
1938       Result += "|";
1939       break;
1940     case 'g':
1941       Result += "imr";
1942       break;
1943     case '[': {
1944       assert(OutCons &&
1945              "Must pass output names to constraints with a symbolic name");
1946       unsigned Index;
1947       bool result = Target.resolveSymbolicName(Constraint, *OutCons, Index);
1948       assert(result && "Could not resolve symbolic name"); (void)result;
1949       Result += llvm::utostr(Index);
1950       break;
1951     }
1952     }
1953 
1954     Constraint++;
1955   }
1956 
1957   return Result;
1958 }
1959 
1960 /// AddVariableConstraints - Look at AsmExpr and if it is a variable declared
1961 /// as using a particular register add that as a constraint that will be used
1962 /// in this asm stmt.
1963 static std::string
1964 AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr,
1965                        const TargetInfo &Target, CodeGenModule &CGM,
1966                        const AsmStmt &Stmt, const bool EarlyClobber,
1967                        std::string *GCCReg = nullptr) {
1968   const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr);
1969   if (!AsmDeclRef)
1970     return Constraint;
1971   const ValueDecl &Value = *AsmDeclRef->getDecl();
1972   const VarDecl *Variable = dyn_cast<VarDecl>(&Value);
1973   if (!Variable)
1974     return Constraint;
1975   if (Variable->getStorageClass() != SC_Register)
1976     return Constraint;
1977   AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>();
1978   if (!Attr)
1979     return Constraint;
1980   StringRef Register = Attr->getLabel();
1981   assert(Target.isValidGCCRegisterName(Register));
1982   // We're using validateOutputConstraint here because we only care if
1983   // this is a register constraint.
1984   TargetInfo::ConstraintInfo Info(Constraint, "");
1985   if (Target.validateOutputConstraint(Info) &&
1986       !Info.allowsRegister()) {
1987     CGM.ErrorUnsupported(&Stmt, "__asm__");
1988     return Constraint;
1989   }
1990   // Canonicalize the register here before returning it.
1991   Register = Target.getNormalizedGCCRegisterName(Register);
1992   if (GCCReg != nullptr)
1993     *GCCReg = Register.str();
1994   return (EarlyClobber ? "&{" : "{") + Register.str() + "}";
1995 }
1996 
1997 llvm::Value*
1998 CodeGenFunction::EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
1999                                     LValue InputValue, QualType InputType,
2000                                     std::string &ConstraintStr,
2001                                     SourceLocation Loc) {
2002   llvm::Value *Arg;
2003   if (Info.allowsRegister() || !Info.allowsMemory()) {
2004     if (CodeGenFunction::hasScalarEvaluationKind(InputType)) {
2005       Arg = EmitLoadOfLValue(InputValue, Loc).getScalarVal();
2006     } else {
2007       llvm::Type *Ty = ConvertType(InputType);
2008       uint64_t Size = CGM.getDataLayout().getTypeSizeInBits(Ty);
2009       if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
2010         Ty = llvm::IntegerType::get(getLLVMContext(), Size);
2011         Ty = llvm::PointerType::getUnqual(Ty);
2012 
2013         Arg = Builder.CreateLoad(
2014             Builder.CreateBitCast(InputValue.getAddress(*this), Ty));
2015       } else {
2016         Arg = InputValue.getPointer(*this);
2017         ConstraintStr += '*';
2018       }
2019     }
2020   } else {
2021     Arg = InputValue.getPointer(*this);
2022     ConstraintStr += '*';
2023   }
2024 
2025   return Arg;
2026 }
2027 
2028 llvm::Value* CodeGenFunction::EmitAsmInput(
2029                                          const TargetInfo::ConstraintInfo &Info,
2030                                            const Expr *InputExpr,
2031                                            std::string &ConstraintStr) {
2032   // If this can't be a register or memory, i.e., has to be a constant
2033   // (immediate or symbolic), try to emit it as such.
2034   if (!Info.allowsRegister() && !Info.allowsMemory()) {
2035     if (Info.requiresImmediateConstant()) {
2036       Expr::EvalResult EVResult;
2037       InputExpr->EvaluateAsRValue(EVResult, getContext(), true);
2038 
2039       llvm::APSInt IntResult;
2040       if (EVResult.Val.toIntegralConstant(IntResult, InputExpr->getType(),
2041                                           getContext()))
2042         return llvm::ConstantInt::get(getLLVMContext(), IntResult);
2043     }
2044 
2045     Expr::EvalResult Result;
2046     if (InputExpr->EvaluateAsInt(Result, getContext()))
2047       return llvm::ConstantInt::get(getLLVMContext(), Result.Val.getInt());
2048   }
2049 
2050   if (Info.allowsRegister() || !Info.allowsMemory())
2051     if (CodeGenFunction::hasScalarEvaluationKind(InputExpr->getType()))
2052       return EmitScalarExpr(InputExpr);
2053   if (InputExpr->getStmtClass() == Expr::CXXThisExprClass)
2054     return EmitScalarExpr(InputExpr);
2055   InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
2056   LValue Dest = EmitLValue(InputExpr);
2057   return EmitAsmInputLValue(Info, Dest, InputExpr->getType(), ConstraintStr,
2058                             InputExpr->getExprLoc());
2059 }
2060 
2061 /// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
2062 /// asm call instruction.  The !srcloc MDNode contains a list of constant
2063 /// integers which are the source locations of the start of each line in the
2064 /// asm.
2065 static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
2066                                       CodeGenFunction &CGF) {
2067   SmallVector<llvm::Metadata *, 8> Locs;
2068   // Add the location of the first line to the MDNode.
2069   Locs.push_back(llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2070       CGF.Int32Ty, Str->getBeginLoc().getRawEncoding())));
2071   StringRef StrVal = Str->getString();
2072   if (!StrVal.empty()) {
2073     const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
2074     const LangOptions &LangOpts = CGF.CGM.getLangOpts();
2075     unsigned StartToken = 0;
2076     unsigned ByteOffset = 0;
2077 
2078     // Add the location of the start of each subsequent line of the asm to the
2079     // MDNode.
2080     for (unsigned i = 0, e = StrVal.size() - 1; i != e; ++i) {
2081       if (StrVal[i] != '\n') continue;
2082       SourceLocation LineLoc = Str->getLocationOfByte(
2083           i + 1, SM, LangOpts, CGF.getTarget(), &StartToken, &ByteOffset);
2084       Locs.push_back(llvm::ConstantAsMetadata::get(
2085           llvm::ConstantInt::get(CGF.Int32Ty, LineLoc.getRawEncoding())));
2086     }
2087   }
2088 
2089   return llvm::MDNode::get(CGF.getLLVMContext(), Locs);
2090 }
2091 
2092 static void UpdateAsmCallInst(llvm::CallBase &Result, bool HasSideEffect,
2093                               bool ReadOnly, bool ReadNone, bool NoMerge,
2094                               const AsmStmt &S,
2095                               const std::vector<llvm::Type *> &ResultRegTypes,
2096                               CodeGenFunction &CGF,
2097                               std::vector<llvm::Value *> &RegResults) {
2098   Result.addAttribute(llvm::AttributeList::FunctionIndex,
2099                       llvm::Attribute::NoUnwind);
2100   if (NoMerge)
2101     Result.addAttribute(llvm::AttributeList::FunctionIndex,
2102                         llvm::Attribute::NoMerge);
2103   // Attach readnone and readonly attributes.
2104   if (!HasSideEffect) {
2105     if (ReadNone)
2106       Result.addAttribute(llvm::AttributeList::FunctionIndex,
2107                           llvm::Attribute::ReadNone);
2108     else if (ReadOnly)
2109       Result.addAttribute(llvm::AttributeList::FunctionIndex,
2110                           llvm::Attribute::ReadOnly);
2111   }
2112 
2113   // Slap the source location of the inline asm into a !srcloc metadata on the
2114   // call.
2115   if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(&S))
2116     Result.setMetadata("srcloc",
2117                        getAsmSrcLocInfo(gccAsmStmt->getAsmString(), CGF));
2118   else {
2119     // At least put the line number on MS inline asm blobs.
2120     llvm::Constant *Loc = llvm::ConstantInt::get(CGF.Int32Ty,
2121                                         S.getAsmLoc().getRawEncoding());
2122     Result.setMetadata("srcloc",
2123                        llvm::MDNode::get(CGF.getLLVMContext(),
2124                                          llvm::ConstantAsMetadata::get(Loc)));
2125   }
2126 
2127   if (CGF.getLangOpts().assumeFunctionsAreConvergent())
2128     // Conservatively, mark all inline asm blocks in CUDA or OpenCL as
2129     // convergent (meaning, they may call an intrinsically convergent op, such
2130     // as bar.sync, and so can't have certain optimizations applied around
2131     // them).
2132     Result.addAttribute(llvm::AttributeList::FunctionIndex,
2133                         llvm::Attribute::Convergent);
2134   // Extract all of the register value results from the asm.
2135   if (ResultRegTypes.size() == 1) {
2136     RegResults.push_back(&Result);
2137   } else {
2138     for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
2139       llvm::Value *Tmp = CGF.Builder.CreateExtractValue(&Result, i, "asmresult");
2140       RegResults.push_back(Tmp);
2141     }
2142   }
2143 }
2144 
2145 void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
2146   // Assemble the final asm string.
2147   std::string AsmString = S.generateAsmString(getContext());
2148 
2149   // Get all the output and input constraints together.
2150   SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
2151   SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
2152 
2153   for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
2154     StringRef Name;
2155     if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
2156       Name = GAS->getOutputName(i);
2157     TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i), Name);
2158     bool IsValid = getTarget().validateOutputConstraint(Info); (void)IsValid;
2159     assert(IsValid && "Failed to parse output constraint");
2160     OutputConstraintInfos.push_back(Info);
2161   }
2162 
2163   for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
2164     StringRef Name;
2165     if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
2166       Name = GAS->getInputName(i);
2167     TargetInfo::ConstraintInfo Info(S.getInputConstraint(i), Name);
2168     bool IsValid =
2169       getTarget().validateInputConstraint(OutputConstraintInfos, Info);
2170     assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
2171     InputConstraintInfos.push_back(Info);
2172   }
2173 
2174   std::string Constraints;
2175 
2176   std::vector<LValue> ResultRegDests;
2177   std::vector<QualType> ResultRegQualTys;
2178   std::vector<llvm::Type *> ResultRegTypes;
2179   std::vector<llvm::Type *> ResultTruncRegTypes;
2180   std::vector<llvm::Type *> ArgTypes;
2181   std::vector<llvm::Value*> Args;
2182   llvm::BitVector ResultTypeRequiresCast;
2183 
2184   // Keep track of inout constraints.
2185   std::string InOutConstraints;
2186   std::vector<llvm::Value*> InOutArgs;
2187   std::vector<llvm::Type*> InOutArgTypes;
2188 
2189   // Keep track of out constraints for tied input operand.
2190   std::vector<std::string> OutputConstraints;
2191 
2192   // Keep track of defined physregs.
2193   llvm::SmallSet<std::string, 8> PhysRegOutputs;
2194 
2195   // An inline asm can be marked readonly if it meets the following conditions:
2196   //  - it doesn't have any sideeffects
2197   //  - it doesn't clobber memory
2198   //  - it doesn't return a value by-reference
2199   // It can be marked readnone if it doesn't have any input memory constraints
2200   // in addition to meeting the conditions listed above.
2201   bool ReadOnly = true, ReadNone = true;
2202 
2203   for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
2204     TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
2205 
2206     // Simplify the output constraint.
2207     std::string OutputConstraint(S.getOutputConstraint(i));
2208     OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1,
2209                                           getTarget(), &OutputConstraintInfos);
2210 
2211     const Expr *OutExpr = S.getOutputExpr(i);
2212     OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
2213 
2214     std::string GCCReg;
2215     OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr,
2216                                               getTarget(), CGM, S,
2217                                               Info.earlyClobber(),
2218                                               &GCCReg);
2219     // Give an error on multiple outputs to same physreg.
2220     if (!GCCReg.empty() && !PhysRegOutputs.insert(GCCReg).second)
2221       CGM.Error(S.getAsmLoc(), "multiple outputs to hard register: " + GCCReg);
2222 
2223     OutputConstraints.push_back(OutputConstraint);
2224     LValue Dest = EmitLValue(OutExpr);
2225     if (!Constraints.empty())
2226       Constraints += ',';
2227 
2228     // If this is a register output, then make the inline asm return it
2229     // by-value.  If this is a memory result, return the value by-reference.
2230     bool isScalarizableAggregate =
2231         hasAggregateEvaluationKind(OutExpr->getType());
2232     if (!Info.allowsMemory() && (hasScalarEvaluationKind(OutExpr->getType()) ||
2233                                  isScalarizableAggregate)) {
2234       Constraints += "=" + OutputConstraint;
2235       ResultRegQualTys.push_back(OutExpr->getType());
2236       ResultRegDests.push_back(Dest);
2237       ResultTruncRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
2238       if (Info.allowsRegister() && isScalarizableAggregate) {
2239         ResultTypeRequiresCast.push_back(true);
2240         unsigned Size = getContext().getTypeSize(OutExpr->getType());
2241         llvm::Type *ConvTy = llvm::IntegerType::get(getLLVMContext(), Size);
2242         ResultRegTypes.push_back(ConvTy);
2243       } else {
2244         ResultTypeRequiresCast.push_back(false);
2245         ResultRegTypes.push_back(ResultTruncRegTypes.back());
2246       }
2247       // If this output is tied to an input, and if the input is larger, then
2248       // we need to set the actual result type of the inline asm node to be the
2249       // same as the input type.
2250       if (Info.hasMatchingInput()) {
2251         unsigned InputNo;
2252         for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
2253           TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
2254           if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
2255             break;
2256         }
2257         assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
2258 
2259         QualType InputTy = S.getInputExpr(InputNo)->getType();
2260         QualType OutputType = OutExpr->getType();
2261 
2262         uint64_t InputSize = getContext().getTypeSize(InputTy);
2263         if (getContext().getTypeSize(OutputType) < InputSize) {
2264           // Form the asm to return the value as a larger integer or fp type.
2265           ResultRegTypes.back() = ConvertType(InputTy);
2266         }
2267       }
2268       if (llvm::Type* AdjTy =
2269             getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
2270                                                  ResultRegTypes.back()))
2271         ResultRegTypes.back() = AdjTy;
2272       else {
2273         CGM.getDiags().Report(S.getAsmLoc(),
2274                               diag::err_asm_invalid_type_in_input)
2275             << OutExpr->getType() << OutputConstraint;
2276       }
2277 
2278       // Update largest vector width for any vector types.
2279       if (auto *VT = dyn_cast<llvm::VectorType>(ResultRegTypes.back()))
2280         LargestVectorWidth =
2281             std::max((uint64_t)LargestVectorWidth,
2282                      VT->getPrimitiveSizeInBits().getKnownMinSize());
2283     } else {
2284       ArgTypes.push_back(Dest.getAddress(*this).getType());
2285       Args.push_back(Dest.getPointer(*this));
2286       Constraints += "=*";
2287       Constraints += OutputConstraint;
2288       ReadOnly = ReadNone = false;
2289     }
2290 
2291     if (Info.isReadWrite()) {
2292       InOutConstraints += ',';
2293 
2294       const Expr *InputExpr = S.getOutputExpr(i);
2295       llvm::Value *Arg = EmitAsmInputLValue(Info, Dest, InputExpr->getType(),
2296                                             InOutConstraints,
2297                                             InputExpr->getExprLoc());
2298 
2299       if (llvm::Type* AdjTy =
2300           getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
2301                                                Arg->getType()))
2302         Arg = Builder.CreateBitCast(Arg, AdjTy);
2303 
2304       // Update largest vector width for any vector types.
2305       if (auto *VT = dyn_cast<llvm::VectorType>(Arg->getType()))
2306         LargestVectorWidth =
2307             std::max((uint64_t)LargestVectorWidth,
2308                      VT->getPrimitiveSizeInBits().getKnownMinSize());
2309       // Only tie earlyclobber physregs.
2310       if (Info.allowsRegister() && (GCCReg.empty() || Info.earlyClobber()))
2311         InOutConstraints += llvm::utostr(i);
2312       else
2313         InOutConstraints += OutputConstraint;
2314 
2315       InOutArgTypes.push_back(Arg->getType());
2316       InOutArgs.push_back(Arg);
2317     }
2318   }
2319 
2320   // If this is a Microsoft-style asm blob, store the return registers (EAX:EDX)
2321   // to the return value slot. Only do this when returning in registers.
2322   if (isa<MSAsmStmt>(&S)) {
2323     const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
2324     if (RetAI.isDirect() || RetAI.isExtend()) {
2325       // Make a fake lvalue for the return value slot.
2326       LValue ReturnSlot = MakeAddrLValue(ReturnValue, FnRetTy);
2327       CGM.getTargetCodeGenInfo().addReturnRegisterOutputs(
2328           *this, ReturnSlot, Constraints, ResultRegTypes, ResultTruncRegTypes,
2329           ResultRegDests, AsmString, S.getNumOutputs());
2330       SawAsmBlock = true;
2331     }
2332   }
2333 
2334   for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
2335     const Expr *InputExpr = S.getInputExpr(i);
2336 
2337     TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
2338 
2339     if (Info.allowsMemory())
2340       ReadNone = false;
2341 
2342     if (!Constraints.empty())
2343       Constraints += ',';
2344 
2345     // Simplify the input constraint.
2346     std::string InputConstraint(S.getInputConstraint(i));
2347     InputConstraint = SimplifyConstraint(InputConstraint.c_str(), getTarget(),
2348                                          &OutputConstraintInfos);
2349 
2350     InputConstraint = AddVariableConstraints(
2351         InputConstraint, *InputExpr->IgnoreParenNoopCasts(getContext()),
2352         getTarget(), CGM, S, false /* No EarlyClobber */);
2353 
2354     std::string ReplaceConstraint (InputConstraint);
2355     llvm::Value *Arg = EmitAsmInput(Info, InputExpr, Constraints);
2356 
2357     // If this input argument is tied to a larger output result, extend the
2358     // input to be the same size as the output.  The LLVM backend wants to see
2359     // the input and output of a matching constraint be the same size.  Note
2360     // that GCC does not define what the top bits are here.  We use zext because
2361     // that is usually cheaper, but LLVM IR should really get an anyext someday.
2362     if (Info.hasTiedOperand()) {
2363       unsigned Output = Info.getTiedOperand();
2364       QualType OutputType = S.getOutputExpr(Output)->getType();
2365       QualType InputTy = InputExpr->getType();
2366 
2367       if (getContext().getTypeSize(OutputType) >
2368           getContext().getTypeSize(InputTy)) {
2369         // Use ptrtoint as appropriate so that we can do our extension.
2370         if (isa<llvm::PointerType>(Arg->getType()))
2371           Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
2372         llvm::Type *OutputTy = ConvertType(OutputType);
2373         if (isa<llvm::IntegerType>(OutputTy))
2374           Arg = Builder.CreateZExt(Arg, OutputTy);
2375         else if (isa<llvm::PointerType>(OutputTy))
2376           Arg = Builder.CreateZExt(Arg, IntPtrTy);
2377         else {
2378           assert(OutputTy->isFloatingPointTy() && "Unexpected output type");
2379           Arg = Builder.CreateFPExt(Arg, OutputTy);
2380         }
2381       }
2382       // Deal with the tied operands' constraint code in adjustInlineAsmType.
2383       ReplaceConstraint = OutputConstraints[Output];
2384     }
2385     if (llvm::Type* AdjTy =
2386           getTargetHooks().adjustInlineAsmType(*this, ReplaceConstraint,
2387                                                    Arg->getType()))
2388       Arg = Builder.CreateBitCast(Arg, AdjTy);
2389     else
2390       CGM.getDiags().Report(S.getAsmLoc(), diag::err_asm_invalid_type_in_input)
2391           << InputExpr->getType() << InputConstraint;
2392 
2393     // Update largest vector width for any vector types.
2394     if (auto *VT = dyn_cast<llvm::VectorType>(Arg->getType()))
2395       LargestVectorWidth =
2396           std::max((uint64_t)LargestVectorWidth,
2397                    VT->getPrimitiveSizeInBits().getKnownMinSize());
2398 
2399     ArgTypes.push_back(Arg->getType());
2400     Args.push_back(Arg);
2401     Constraints += InputConstraint;
2402   }
2403 
2404   // Labels
2405   SmallVector<llvm::BasicBlock *, 16> Transfer;
2406   llvm::BasicBlock *Fallthrough = nullptr;
2407   bool IsGCCAsmGoto = false;
2408   if (const auto *GS =  dyn_cast<GCCAsmStmt>(&S)) {
2409     IsGCCAsmGoto = GS->isAsmGoto();
2410     if (IsGCCAsmGoto) {
2411       for (const auto *E : GS->labels()) {
2412         JumpDest Dest = getJumpDestForLabel(E->getLabel());
2413         Transfer.push_back(Dest.getBlock());
2414         llvm::BlockAddress *BA =
2415             llvm::BlockAddress::get(CurFn, Dest.getBlock());
2416         Args.push_back(BA);
2417         ArgTypes.push_back(BA->getType());
2418         if (!Constraints.empty())
2419           Constraints += ',';
2420         Constraints += 'X';
2421       }
2422       Fallthrough = createBasicBlock("asm.fallthrough");
2423     }
2424   }
2425 
2426   // Append the "input" part of inout constraints last.
2427   for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
2428     ArgTypes.push_back(InOutArgTypes[i]);
2429     Args.push_back(InOutArgs[i]);
2430   }
2431   Constraints += InOutConstraints;
2432 
2433   // Clobbers
2434   for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
2435     StringRef Clobber = S.getClobber(i);
2436 
2437     if (Clobber == "memory")
2438       ReadOnly = ReadNone = false;
2439     else if (Clobber != "cc") {
2440       Clobber = getTarget().getNormalizedGCCRegisterName(Clobber);
2441       if (CGM.getCodeGenOpts().StackClashProtector &&
2442           getTarget().isSPRegName(Clobber)) {
2443         CGM.getDiags().Report(S.getAsmLoc(),
2444                               diag::warn_stack_clash_protection_inline_asm);
2445       }
2446     }
2447 
2448     if (!Constraints.empty())
2449       Constraints += ',';
2450 
2451     Constraints += "~{";
2452     Constraints += Clobber;
2453     Constraints += '}';
2454   }
2455 
2456   // Add machine specific clobbers
2457   std::string MachineClobbers = getTarget().getClobbers();
2458   if (!MachineClobbers.empty()) {
2459     if (!Constraints.empty())
2460       Constraints += ',';
2461     Constraints += MachineClobbers;
2462   }
2463 
2464   llvm::Type *ResultType;
2465   if (ResultRegTypes.empty())
2466     ResultType = VoidTy;
2467   else if (ResultRegTypes.size() == 1)
2468     ResultType = ResultRegTypes[0];
2469   else
2470     ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes);
2471 
2472   llvm::FunctionType *FTy =
2473     llvm::FunctionType::get(ResultType, ArgTypes, false);
2474 
2475   bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0;
2476   llvm::InlineAsm::AsmDialect AsmDialect = isa<MSAsmStmt>(&S) ?
2477     llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT;
2478   llvm::InlineAsm *IA =
2479     llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect,
2480                          /* IsAlignStack */ false, AsmDialect);
2481   std::vector<llvm::Value*> RegResults;
2482   if (IsGCCAsmGoto) {
2483     llvm::CallBrInst *Result =
2484         Builder.CreateCallBr(IA, Fallthrough, Transfer, Args);
2485     EmitBlock(Fallthrough);
2486     UpdateAsmCallInst(cast<llvm::CallBase>(*Result), HasSideEffect, ReadOnly,
2487                       ReadNone, InNoMergeAttributedStmt, S, ResultRegTypes,
2488                       *this, RegResults);
2489   } else {
2490     llvm::CallInst *Result =
2491         Builder.CreateCall(IA, Args, getBundlesForFunclet(IA));
2492     UpdateAsmCallInst(cast<llvm::CallBase>(*Result), HasSideEffect, ReadOnly,
2493                       ReadNone, InNoMergeAttributedStmt, S, ResultRegTypes,
2494                       *this, RegResults);
2495   }
2496 
2497   assert(RegResults.size() == ResultRegTypes.size());
2498   assert(RegResults.size() == ResultTruncRegTypes.size());
2499   assert(RegResults.size() == ResultRegDests.size());
2500   // ResultRegDests can be also populated by addReturnRegisterOutputs() above,
2501   // in which case its size may grow.
2502   assert(ResultTypeRequiresCast.size() <= ResultRegDests.size());
2503   for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
2504     llvm::Value *Tmp = RegResults[i];
2505 
2506     // If the result type of the LLVM IR asm doesn't match the result type of
2507     // the expression, do the conversion.
2508     if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
2509       llvm::Type *TruncTy = ResultTruncRegTypes[i];
2510 
2511       // Truncate the integer result to the right size, note that TruncTy can be
2512       // a pointer.
2513       if (TruncTy->isFloatingPointTy())
2514         Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
2515       else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
2516         uint64_t ResSize = CGM.getDataLayout().getTypeSizeInBits(TruncTy);
2517         Tmp = Builder.CreateTrunc(Tmp,
2518                    llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize));
2519         Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
2520       } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
2521         uint64_t TmpSize =CGM.getDataLayout().getTypeSizeInBits(Tmp->getType());
2522         Tmp = Builder.CreatePtrToInt(Tmp,
2523                    llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize));
2524         Tmp = Builder.CreateTrunc(Tmp, TruncTy);
2525       } else if (TruncTy->isIntegerTy()) {
2526         Tmp = Builder.CreateZExtOrTrunc(Tmp, TruncTy);
2527       } else if (TruncTy->isVectorTy()) {
2528         Tmp = Builder.CreateBitCast(Tmp, TruncTy);
2529       }
2530     }
2531 
2532     LValue Dest = ResultRegDests[i];
2533     // ResultTypeRequiresCast elements correspond to the first
2534     // ResultTypeRequiresCast.size() elements of RegResults.
2535     if ((i < ResultTypeRequiresCast.size()) && ResultTypeRequiresCast[i]) {
2536       unsigned Size = getContext().getTypeSize(ResultRegQualTys[i]);
2537       Address A = Builder.CreateBitCast(Dest.getAddress(*this),
2538                                         ResultRegTypes[i]->getPointerTo());
2539       QualType Ty = getContext().getIntTypeForBitwidth(Size, /*Signed*/ false);
2540       if (Ty.isNull()) {
2541         const Expr *OutExpr = S.getOutputExpr(i);
2542         CGM.Error(
2543             OutExpr->getExprLoc(),
2544             "impossible constraint in asm: can't store value into a register");
2545         return;
2546       }
2547       Dest = MakeAddrLValue(A, Ty);
2548     }
2549     EmitStoreThroughLValue(RValue::get(Tmp), Dest);
2550   }
2551 }
2552 
2553 LValue CodeGenFunction::InitCapturedStruct(const CapturedStmt &S) {
2554   const RecordDecl *RD = S.getCapturedRecordDecl();
2555   QualType RecordTy = getContext().getRecordType(RD);
2556 
2557   // Initialize the captured struct.
2558   LValue SlotLV =
2559     MakeAddrLValue(CreateMemTemp(RecordTy, "agg.captured"), RecordTy);
2560 
2561   RecordDecl::field_iterator CurField = RD->field_begin();
2562   for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
2563                                                  E = S.capture_init_end();
2564        I != E; ++I, ++CurField) {
2565     LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
2566     if (CurField->hasCapturedVLAType()) {
2567       EmitLambdaVLACapture(CurField->getCapturedVLAType(), LV);
2568     } else {
2569       EmitInitializerForField(*CurField, LV, *I);
2570     }
2571   }
2572 
2573   return SlotLV;
2574 }
2575 
2576 /// Generate an outlined function for the body of a CapturedStmt, store any
2577 /// captured variables into the captured struct, and call the outlined function.
2578 llvm::Function *
2579 CodeGenFunction::EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K) {
2580   LValue CapStruct = InitCapturedStruct(S);
2581 
2582   // Emit the CapturedDecl
2583   CodeGenFunction CGF(CGM, true);
2584   CGCapturedStmtRAII CapInfoRAII(CGF, new CGCapturedStmtInfo(S, K));
2585   llvm::Function *F = CGF.GenerateCapturedStmtFunction(S);
2586   delete CGF.CapturedStmtInfo;
2587 
2588   // Emit call to the helper function.
2589   EmitCallOrInvoke(F, CapStruct.getPointer(*this));
2590 
2591   return F;
2592 }
2593 
2594 Address CodeGenFunction::GenerateCapturedStmtArgument(const CapturedStmt &S) {
2595   LValue CapStruct = InitCapturedStruct(S);
2596   return CapStruct.getAddress(*this);
2597 }
2598 
2599 /// Creates the outlined function for a CapturedStmt.
2600 llvm::Function *
2601 CodeGenFunction::GenerateCapturedStmtFunction(const CapturedStmt &S) {
2602   assert(CapturedStmtInfo &&
2603     "CapturedStmtInfo should be set when generating the captured function");
2604   const CapturedDecl *CD = S.getCapturedDecl();
2605   const RecordDecl *RD = S.getCapturedRecordDecl();
2606   SourceLocation Loc = S.getBeginLoc();
2607   assert(CD->hasBody() && "missing CapturedDecl body");
2608 
2609   // Build the argument list.
2610   ASTContext &Ctx = CGM.getContext();
2611   FunctionArgList Args;
2612   Args.append(CD->param_begin(), CD->param_end());
2613 
2614   // Create the function declaration.
2615   const CGFunctionInfo &FuncInfo =
2616     CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args);
2617   llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
2618 
2619   llvm::Function *F =
2620     llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
2621                            CapturedStmtInfo->getHelperName(), &CGM.getModule());
2622   CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
2623   if (CD->isNothrow())
2624     F->addFnAttr(llvm::Attribute::NoUnwind);
2625 
2626   // Generate the function.
2627   StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
2628                 CD->getBody()->getBeginLoc());
2629   // Set the context parameter in CapturedStmtInfo.
2630   Address DeclPtr = GetAddrOfLocalVar(CD->getContextParam());
2631   CapturedStmtInfo->setContextValue(Builder.CreateLoad(DeclPtr));
2632 
2633   // Initialize variable-length arrays.
2634   LValue Base = MakeNaturalAlignAddrLValue(CapturedStmtInfo->getContextValue(),
2635                                            Ctx.getTagDeclType(RD));
2636   for (auto *FD : RD->fields()) {
2637     if (FD->hasCapturedVLAType()) {
2638       auto *ExprArg =
2639           EmitLoadOfLValue(EmitLValueForField(Base, FD), S.getBeginLoc())
2640               .getScalarVal();
2641       auto VAT = FD->getCapturedVLAType();
2642       VLASizeMap[VAT->getSizeExpr()] = ExprArg;
2643     }
2644   }
2645 
2646   // If 'this' is captured, load it into CXXThisValue.
2647   if (CapturedStmtInfo->isCXXThisExprCaptured()) {
2648     FieldDecl *FD = CapturedStmtInfo->getThisFieldDecl();
2649     LValue ThisLValue = EmitLValueForField(Base, FD);
2650     CXXThisValue = EmitLoadOfLValue(ThisLValue, Loc).getScalarVal();
2651   }
2652 
2653   PGO.assignRegionCounters(GlobalDecl(CD), F);
2654   CapturedStmtInfo->EmitBody(*this, CD->getBody());
2655   FinishFunction(CD->getBodyRBrace());
2656 
2657   return F;
2658 }
2659