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