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