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