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