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