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