blob: daad3f5e7988ad05fd74b1c9791de7c058171087 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Stmt nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
15#include "CodeGenModule.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "CodeGenFunction.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000017#include "clang/AST/StmtVisitor.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000018#include "clang/Basic/TargetInfo.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000019#include "llvm/InlineAsm.h"
20#include "llvm/ADT/StringExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021using namespace clang;
22using namespace CodeGen;
23
24//===----------------------------------------------------------------------===//
25// Statement Emission
26//===----------------------------------------------------------------------===//
27
28void CodeGenFunction::EmitStmt(const Stmt *S) {
29 assert(S && "Null statement?");
Daniel Dunbara448fb22008-11-11 23:11:34 +000030
31 // If we happen to be at an unreachable point just create a dummy
32 // basic block to hold the code. We could change parts of irgen to
33 // simply not generate this code, but this situation is rare and
34 // probably not worth the effort.
35 // FIXME: Verify previous performance/effort claim.
36 EnsureInsertPoint();
Reid Spencer5f016e22007-07-11 17:01:13 +000037
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000038 // Generate stoppoints if we are emitting debug info.
39 // Beginning of a Compound Statement (e.g. an opening '{') does not produce
40 // executable code. So do not generate a stoppoint for that.
41 CGDebugInfo *DI = CGM.getDebugInfo();
42 if (DI && S->getStmtClass() != Stmt::CompoundStmtClass) {
Daniel Dunbar66031a52008-10-17 16:15:48 +000043 DI->setLocation(S->getLocStart());
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000044 DI->EmitStopPoint(CurFn, Builder);
45 }
46
Reid Spencer5f016e22007-07-11 17:01:13 +000047 switch (S->getStmtClass()) {
48 default:
Chris Lattner1e4d21e2007-08-26 22:58:05 +000049 // Must be an expression in a stmt context. Emit the value (to get
50 // side-effects) and ignore the result.
Reid Spencer5f016e22007-07-11 17:01:13 +000051 if (const Expr *E = dyn_cast<Expr>(S)) {
Chris Lattner1e4d21e2007-08-26 22:58:05 +000052 if (!hasAggregateLLVMType(E->getType()))
53 EmitScalarExpr(E);
Chris Lattner9b2dc282008-04-04 16:54:41 +000054 else if (E->getType()->isAnyComplexType())
Chris Lattner1e4d21e2007-08-26 22:58:05 +000055 EmitComplexExpr(E);
56 else
57 EmitAggExpr(E, 0, false);
Reid Spencer5f016e22007-07-11 17:01:13 +000058 } else {
Daniel Dunbar488e9932008-08-16 00:56:44 +000059 ErrorUnsupported(S, "statement");
Reid Spencer5f016e22007-07-11 17:01:13 +000060 }
61 break;
62 case Stmt::NullStmtClass: break;
63 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
64 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
65 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
Daniel Dunbar0ffb1252008-08-04 16:51:22 +000066 case Stmt::IndirectGotoStmtClass:
67 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000068
69 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
70 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
71 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
72 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
73
74 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
75 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Chris Lattnerda138702007-07-16 21:28:45 +000076
Daniel Dunbara4275d12008-10-02 18:02:06 +000077 case Stmt::BreakStmtClass:
78 // FIXME: Implement break in @try or @catch blocks.
79 if (!ObjCEHStack.empty()) {
80 CGM.ErrorUnsupported(S, "continue inside an Obj-C exception block");
81 return;
82 }
83 EmitBreakStmt();
84 break;
85
86 case Stmt::ContinueStmtClass:
87 // FIXME: Implement continue in @try or @catch blocks.
88 if (!ObjCEHStack.empty()) {
89 CGM.ErrorUnsupported(S, "continue inside an Obj-C exception block");
90 return;
91 }
92 EmitContinueStmt();
93 break;
94
Devang Patel51b09f22007-10-04 23:45:31 +000095 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
96 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
97 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000098 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000099
100 case Stmt::ObjCAtTryStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000101 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
102 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000103 case Stmt::ObjCAtCatchStmtClass:
Anders Carlssondde0a942008-09-11 09:15:33 +0000104 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
105 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000106 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000107 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000108 break;
109 case Stmt::ObjCAtThrowStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000110 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000111 break;
112 case Stmt::ObjCAtSynchronizedStmtClass:
113 ErrorUnsupported(S, "@synchronized statement");
114 break;
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000115 case Stmt::ObjCForCollectionStmtClass:
116 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000117 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000118 }
119}
120
Chris Lattner33793202007-08-31 22:09:40 +0000121/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
122/// this captures the expression result of the last sub-statement and returns it
123/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +0000124RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
125 llvm::Value *AggLoc, bool isAggVol) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000126 // FIXME: handle vla's etc.
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000127 CGDebugInfo *DI = CGM.getDebugInfo();
128 if (DI) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000129 DI->setLocation(S.getLBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000130 DI->EmitRegionStart(CurFn, Builder);
131 }
132
Chris Lattner33793202007-08-31 22:09:40 +0000133 for (CompoundStmt::const_body_iterator I = S.body_begin(),
134 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000135 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000136
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000137 if (DI) {
Daniel Dunbara448fb22008-11-11 23:11:34 +0000138 EnsureInsertPoint();
Daniel Dunbar66031a52008-10-17 16:15:48 +0000139 DI->setLocation(S.getRBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000140 DI->EmitRegionEnd(CurFn, Builder);
141 }
142
Chris Lattner33793202007-08-31 22:09:40 +0000143 if (!GetLast)
144 return RValue::get(0);
Chris Lattner9b655512007-08-31 22:49:20 +0000145
Chris Lattner91d723d2008-07-26 20:23:23 +0000146 // We have to special case labels here. They are statements, but when put at
147 // the end of a statement expression, they yield the value of their
148 // subexpression. Handle this by walking through all labels we encounter,
149 // emitting them before we evaluate the subexpr.
150 const Stmt *LastStmt = S.body_back();
151 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
152 EmitLabel(*LS);
153 LastStmt = LS->getSubStmt();
154 }
155
Daniel Dunbara448fb22008-11-11 23:11:34 +0000156 EnsureInsertPoint();
157
Chris Lattner91d723d2008-07-26 20:23:23 +0000158 return EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000159}
160
161void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB) {
Daniel Dunbard57a8712008-11-11 09:41:28 +0000162 // Fall out of the current block (if necessary).
163 EmitBranch(BB);
Reid Spencer5f016e22007-07-11 17:01:13 +0000164 CurFn->getBasicBlockList().push_back(BB);
165 Builder.SetInsertPoint(BB);
166}
167
Daniel Dunbard57a8712008-11-11 09:41:28 +0000168void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
169 // Emit a branch from the current block to the target one if this
170 // was a real block. If this was just a fall-through block after a
171 // terminator, don't emit it.
172 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
173
174 if (!CurBB || CurBB->getTerminator()) {
175 // If there is no insert point or the previous block is already
176 // terminated, don't touch it.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000177 } else {
178 // Otherwise, create a fall-through branch.
179 Builder.CreateBr(Target);
180 }
Daniel Dunbar5e08ad32008-11-11 22:06:59 +0000181
182 Builder.ClearInsertionPoint();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000183}
184
Chris Lattner91d723d2008-07-26 20:23:23 +0000185void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000186 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000187 EmitBlock(NextBB);
Chris Lattner91d723d2008-07-26 20:23:23 +0000188}
189
190
191void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
192 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000193 EmitStmt(S.getSubStmt());
194}
195
196void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000197 // FIXME: Implement goto out in @try or @catch blocks.
198 if (!ObjCEHStack.empty()) {
199 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
200 return;
201 }
202
Daniel Dunbard57a8712008-11-11 09:41:28 +0000203 EmitBranch(getBasicBlockForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000204}
205
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000206void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000207 // FIXME: Implement indirect goto in @try or @catch blocks.
208 if (!ObjCEHStack.empty()) {
209 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
210 return;
211 }
212
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000213 // Emit initial switch which will be patched up later by
214 // EmitIndirectSwitches(). We need a default dest, so we use the
215 // current BB, but this is overwritten.
216 llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
217 llvm::Type::Int32Ty,
218 "addr");
219 llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
220 IndirectSwitches.push_back(I);
221
Daniel Dunbara448fb22008-11-11 23:11:34 +0000222 // Clear the insertion point to indicate we are in unreachable code.
223 Builder.ClearInsertionPoint();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000224}
225
Chris Lattner62b72f62008-11-11 07:24:28 +0000226void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000227 // C99 6.8.4.1: The first substatement is executed if the expression compares
228 // unequal to 0. The condition must be a scalar type.
229 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
230
Chris Lattner62b72f62008-11-11 07:24:28 +0000231 // If we constant folded the condition to true or false, try to avoid emitting
232 // the dead arm at all.
233 if (llvm::ConstantInt *CondCst = dyn_cast<llvm::ConstantInt>(BoolCondVal)) {
234 // Figure out which block (then or else) is executed.
235 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
236 if (!CondCst->getZExtValue())
237 std::swap(Executed, Skipped);
238
239 // If the skipped block has no labels in it, just emit the executed block.
240 // This avoids emitting dead code and simplifies the CFG substantially.
241 if (Skipped == 0 || !ContainsLabel(Skipped)) {
242 if (Executed)
243 EmitStmt(Executed);
244 return;
245 }
246 }
247
Daniel Dunbar55e87422008-11-11 02:29:29 +0000248 llvm::BasicBlock *ContBlock = createBasicBlock("ifend");
249 llvm::BasicBlock *ThenBlock = createBasicBlock("ifthen");
Reid Spencer5f016e22007-07-11 17:01:13 +0000250 llvm::BasicBlock *ElseBlock = ContBlock;
251
252 if (S.getElse())
Daniel Dunbar55e87422008-11-11 02:29:29 +0000253 ElseBlock = createBasicBlock("ifelse");
Reid Spencer5f016e22007-07-11 17:01:13 +0000254
255 // Insert the conditional branch.
256 Builder.CreateCondBr(BoolCondVal, ThenBlock, ElseBlock);
257
258 // Emit the 'then' code.
259 EmitBlock(ThenBlock);
260 EmitStmt(S.getThen());
Daniel Dunbard57a8712008-11-11 09:41:28 +0000261 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000262
263 // Emit the 'else' code if present.
264 if (const Stmt *Else = S.getElse()) {
265 EmitBlock(ElseBlock);
266 EmitStmt(Else);
Daniel Dunbard57a8712008-11-11 09:41:28 +0000267 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000268 }
269
270 // Emit the continuation block for code after the if.
271 EmitBlock(ContBlock);
272}
273
274void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000275 // Emit the header for the loop, insert it, which will create an uncond br to
276 // it.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000277 llvm::BasicBlock *LoopHeader = createBasicBlock("whilecond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000278 EmitBlock(LoopHeader);
279
280 // Evaluate the conditional in the while header. C99 6.8.5.1: The evaluation
281 // of the controlling expression takes place before each execution of the loop
282 // body.
283 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000284
285 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000286 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000287 bool EmitBoolCondBranch = true;
288 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
289 if (C->isOne())
290 EmitBoolCondBranch = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000291
292 // Create an exit block for when the condition fails, create a block for the
293 // body of the loop.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000294 llvm::BasicBlock *ExitBlock = createBasicBlock("whileexit");
295 llvm::BasicBlock *LoopBody = createBasicBlock("whilebody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000296
297 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000298 if (EmitBoolCondBranch)
299 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattnerda138702007-07-16 21:28:45 +0000300
301 // Store the blocks to use for break and continue.
302 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Reid Spencer5f016e22007-07-11 17:01:13 +0000303
304 // Emit the loop body.
305 EmitBlock(LoopBody);
306 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000307
308 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000309
310 // Cycle to the condition.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000311 EmitBranch(LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000312
313 // Emit the exit block.
314 EmitBlock(ExitBlock);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000315
316 // If LoopHeader is a simple forwarding block then eliminate it.
317 if (!EmitBoolCondBranch
318 && &LoopHeader->front() == LoopHeader->getTerminator()) {
319 LoopHeader->replaceAllUsesWith(LoopBody);
320 LoopHeader->getTerminator()->eraseFromParent();
321 LoopHeader->eraseFromParent();
322 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000323}
324
325void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000326 // Emit the body for the loop, insert it, which will create an uncond br to
327 // it.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000328 llvm::BasicBlock *LoopBody = createBasicBlock("dobody");
329 llvm::BasicBlock *AfterDo = createBasicBlock("afterdo");
Reid Spencer5f016e22007-07-11 17:01:13 +0000330 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000331
Daniel Dunbar55e87422008-11-11 02:29:29 +0000332 llvm::BasicBlock *DoCond = createBasicBlock("docond");
Chris Lattnerda138702007-07-16 21:28:45 +0000333
334 // Store the blocks to use for break and continue.
335 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Reid Spencer5f016e22007-07-11 17:01:13 +0000336
337 // Emit the body of the loop into the block.
338 EmitStmt(S.getBody());
339
Chris Lattnerda138702007-07-16 21:28:45 +0000340 BreakContinueStack.pop_back();
341
342 EmitBlock(DoCond);
343
Reid Spencer5f016e22007-07-11 17:01:13 +0000344 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
345 // after each execution of the loop body."
346
347 // Evaluate the conditional in the while header.
348 // C99 6.8.5p2/p4: The first substatement is executed if the expression
349 // compares unequal to 0. The condition must be a scalar type.
350 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000351
352 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
353 // to correctly handle break/continue though.
354 bool EmitBoolCondBranch = true;
355 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
356 if (C->isZero())
357 EmitBoolCondBranch = false;
358
Reid Spencer5f016e22007-07-11 17:01:13 +0000359 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000360 if (EmitBoolCondBranch)
361 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000362
363 // Emit the exit block.
364 EmitBlock(AfterDo);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000365
366 // If DoCond is a simple forwarding block then eliminate it.
367 if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
368 DoCond->replaceAllUsesWith(AfterDo);
369 DoCond->getTerminator()->eraseFromParent();
370 DoCond->eraseFromParent();
371 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000372}
373
374void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000375 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
376 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000377 // TODO: We could keep track of whether the loop body contains any
378 // break/continue statements and not create unnecessary blocks (like
379 // "afterfor" for a condless loop) if it doesn't.
380
Reid Spencer5f016e22007-07-11 17:01:13 +0000381 // Evaluate the first part before the loop.
382 if (S.getInit())
383 EmitStmt(S.getInit());
384
385 // Start the loop with a block that tests the condition.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000386 llvm::BasicBlock *CondBlock = createBasicBlock("forcond");
387 llvm::BasicBlock *AfterFor = createBasicBlock("afterfor");
Chris Lattnerda138702007-07-16 21:28:45 +0000388
Reid Spencer5f016e22007-07-11 17:01:13 +0000389 EmitBlock(CondBlock);
390
391 // Evaluate the condition if present. If not, treat it as a non-zero-constant
392 // according to 6.8.5.3p2, aka, true.
393 if (S.getCond()) {
394 // C99 6.8.5p2/p4: The first substatement is executed if the expression
395 // compares unequal to 0. The condition must be a scalar type.
396 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
397
398 // As long as the condition is true, iterate the loop.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000399 llvm::BasicBlock *ForBody = createBasicBlock("forbody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000400 Builder.CreateCondBr(BoolCondVal, ForBody, AfterFor);
401 EmitBlock(ForBody);
402 } else {
403 // Treat it as a non-zero constant. Don't even create a new block for the
404 // body, just fall into it.
405 }
406
Chris Lattnerda138702007-07-16 21:28:45 +0000407 // If the for loop doesn't have an increment we can just use the
408 // condition as the continue block.
409 llvm::BasicBlock *ContinueBlock;
410 if (S.getInc())
Daniel Dunbar55e87422008-11-11 02:29:29 +0000411 ContinueBlock = createBasicBlock("forinc");
Chris Lattnerda138702007-07-16 21:28:45 +0000412 else
413 ContinueBlock = CondBlock;
414
415 // Store the blocks to use for break and continue.
416 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
417
Reid Spencer5f016e22007-07-11 17:01:13 +0000418 // If the condition is true, execute the body of the for stmt.
419 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000420
421 BreakContinueStack.pop_back();
422
Reid Spencer5f016e22007-07-11 17:01:13 +0000423 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000424 if (S.getInc()) {
425 EmitBlock(ContinueBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000426 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000427 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000428
429 // Finally, branch back up to the condition for the next iteration.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000430 EmitBranch(CondBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000431
Chris Lattnerda138702007-07-16 21:28:45 +0000432 // Emit the fall-through block.
433 EmitBlock(AfterFor);
Reid Spencer5f016e22007-07-11 17:01:13 +0000434}
435
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000436void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
437 if (RV.isScalar()) {
438 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
439 } else if (RV.isAggregate()) {
440 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
441 } else {
442 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
443 }
Daniel Dunbard57a8712008-11-11 09:41:28 +0000444 EmitBranch(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000445}
446
Reid Spencer5f016e22007-07-11 17:01:13 +0000447/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
448/// if the function returns void, or may be missing one if the function returns
449/// non-void. Fun stuff :).
450void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000451 // Emit the result value, even if unused, to evalute the side effects.
452 const Expr *RV = S.getRetValue();
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000453
454 // FIXME: Clean this up by using an LValue for ReturnTemp,
455 // EmitStoreThroughLValue, and EmitAnyExpr.
456 if (!ReturnValue) {
457 // Make sure not to return anything, but evaluate the expression
458 // for side effects.
459 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000460 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000461 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000462 // Do nothing (return value is left uninitialized)
Chris Lattner4b0029d2007-08-26 07:14:44 +0000463 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000464 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000465 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000466 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000467 } else {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000468 EmitAggExpr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000469 }
Eli Friedman144ac612008-05-22 01:22:33 +0000470
Daniel Dunbar898d5082008-09-30 01:06:03 +0000471 if (!ObjCEHStack.empty()) {
472 for (ObjCEHStackType::reverse_iterator i = ObjCEHStack.rbegin(),
473 e = ObjCEHStack.rend(); i != e; ++i) {
Daniel Dunbar55e87422008-11-11 02:29:29 +0000474 llvm::BasicBlock *ReturnPad = createBasicBlock("return.pad");
Daniel Dunbar898d5082008-09-30 01:06:03 +0000475 EmitJumpThroughFinally(*i, ReturnPad);
476 EmitBlock(ReturnPad);
477 }
478 }
479
Daniel Dunbard57a8712008-11-11 09:41:28 +0000480 EmitBranch(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000481}
482
483void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000484 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
485 I != E; ++I)
486 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000487}
Chris Lattnerda138702007-07-16 21:28:45 +0000488
489void CodeGenFunction::EmitBreakStmt() {
490 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
491
492 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000493 EmitBranch(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000494}
495
496void CodeGenFunction::EmitContinueStmt() {
497 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
498
499 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000500 EmitBranch(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000501}
Devang Patel51b09f22007-10-04 23:45:31 +0000502
Devang Patelc049e4f2007-10-08 20:57:48 +0000503/// EmitCaseStmtRange - If case statement range is not too big then
504/// add multiple cases to switch instruction, one for each value within
505/// the range. If range is too big then emit "if" condition check.
506void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000507 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000508
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000509 llvm::APSInt LHS = S.getLHS()->getIntegerConstantExprValue(getContext());
510 llvm::APSInt RHS = S.getRHS()->getIntegerConstantExprValue(getContext());
511
Daniel Dunbar16f23572008-07-25 01:11:38 +0000512 // Emit the code for this case. We do this first to make sure it is
513 // properly chained from our predecessor before generating the
514 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000515 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000516 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
517 EmitStmt(S.getSubStmt());
518
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000519 // If range is empty, do nothing.
520 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
521 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000522
523 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000524 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000525 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
526 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000527 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patel2d79d0f2007-10-05 20:54:07 +0000528 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
529 LHS++;
530 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000531 return;
532 }
533
Daniel Dunbar16f23572008-07-25 01:11:38 +0000534 // The range is too big. Emit "if" condition into a new block,
535 // making sure to save and restore the current insertion point.
536 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000537
Daniel Dunbar16f23572008-07-25 01:11:38 +0000538 // Push this test onto the chain of range checks (which terminates
539 // in the default basic block). The switch's default will be changed
540 // to the top of this chain after switch emission is complete.
541 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000542 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000543
Daniel Dunbar16f23572008-07-25 01:11:38 +0000544 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
545 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000546
547 // Emit range check.
548 llvm::Value *Diff =
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000549 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
550 "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000551 llvm::Value *Cond =
552 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
553 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
554
Daniel Dunbar16f23572008-07-25 01:11:38 +0000555 // Restore the appropriate insertion point.
Daniel Dunbara448fb22008-11-11 23:11:34 +0000556 if (RestoreBB)
557 Builder.SetInsertPoint(RestoreBB);
558 else
559 Builder.ClearInsertionPoint();
Devang Patelc049e4f2007-10-08 20:57:48 +0000560}
561
562void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
563 if (S.getRHS()) {
564 EmitCaseStmtRange(S);
565 return;
566 }
567
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000568 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000569 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000570 llvm::APSInt CaseVal = S.getLHS()->getIntegerConstantExprValue(getContext());
Daniel Dunbar55e87422008-11-11 02:29:29 +0000571 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
Devang Patel51b09f22007-10-04 23:45:31 +0000572 EmitStmt(S.getSubStmt());
573}
574
575void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000576 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Daniel Dunbar55e87422008-11-11 02:29:29 +0000577 assert(DefaultBlock->empty() &&
578 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000579 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000580 EmitStmt(S.getSubStmt());
581}
582
583void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
584 llvm::Value *CondV = EmitScalarExpr(S.getCond());
585
586 // Handle nested switch statements.
587 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000588 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000589
Daniel Dunbar16f23572008-07-25 01:11:38 +0000590 // Create basic block to hold stuff that comes after switch
591 // statement. We also need to create a default block now so that
592 // explicit case ranges tests can have a place to jump to on
593 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000594 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
595 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000596 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
597 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000598
Eli Friedmand28a80d2008-05-12 16:08:04 +0000599 // Create basic block for body of switch
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000600 EmitBlock(createBasicBlock("sw.body"));
Eli Friedmand28a80d2008-05-12 16:08:04 +0000601
Devang Patele9b8c0a2007-10-30 20:59:40 +0000602 // All break statements jump to NextBlock. If BreakContinueStack is non empty
603 // then reuse last ContinueBlock.
Devang Patel51b09f22007-10-04 23:45:31 +0000604 llvm::BasicBlock *ContinueBlock = NULL;
605 if (!BreakContinueStack.empty())
606 ContinueBlock = BreakContinueStack.back().ContinueBlock;
607 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
608
609 // Emit switch body.
610 EmitStmt(S.getBody());
611 BreakContinueStack.pop_back();
612
Daniel Dunbar16f23572008-07-25 01:11:38 +0000613 // Update the default block in case explicit case range tests have
614 // been chained on top.
615 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000616
Daniel Dunbar16f23572008-07-25 01:11:38 +0000617 // If a default was never emitted then reroute any jumps to it and
618 // discard.
619 if (!DefaultBlock->getParent()) {
620 DefaultBlock->replaceAllUsesWith(NextBlock);
621 delete DefaultBlock;
622 }
Devang Patel51b09f22007-10-04 23:45:31 +0000623
Daniel Dunbar16f23572008-07-25 01:11:38 +0000624 // Emit continuation.
625 EmitBlock(NextBlock);
626
Devang Patel51b09f22007-10-04 23:45:31 +0000627 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000628 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000629}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000630
Anders Carlssonce179ab2008-11-09 18:54:14 +0000631static std::string ConvertAsmString(const AsmStmt& S, bool &Failed)
632{
633 // FIXME: No need to create new std::string here, we could just make sure
634 // that we don't read past the end of the string data.
635 std::string str(S.getAsmString()->getStrData(),
636 S.getAsmString()->getByteLength());
637 const char *Start = str.c_str();
638
639 unsigned NumOperands = S.getNumOutputs() + S.getNumInputs();
640 bool IsSimple = S.isSimple();
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000641 Failed = false;
642
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000643 static unsigned AsmCounter = 0;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000644 AsmCounter++;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000645 std::string Result;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000646 if (IsSimple) {
647 while (*Start) {
648 switch (*Start) {
649 default:
650 Result += *Start;
651 break;
652 case '$':
653 Result += "$$";
654 break;
655 }
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000656 Start++;
657 }
658
659 return Result;
660 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000661
662 while (*Start) {
663 switch (*Start) {
664 default:
665 Result += *Start;
666 break;
667 case '$':
668 Result += "$$";
669 break;
670 case '%':
671 // Escaped character
672 Start++;
673 if (!*Start) {
674 // FIXME: This should be caught during Sema.
675 assert(0 && "Trailing '%' in asm string.");
676 }
677
678 char EscapedChar = *Start;
679 if (EscapedChar == '%') {
680 // Escaped percentage sign.
681 Result += '%';
Chris Lattner345f7202008-07-26 20:15:14 +0000682 } else if (EscapedChar == '=') {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000683 // Generate an unique ID.
684 Result += llvm::utostr(AsmCounter);
685 } else if (isdigit(EscapedChar)) {
686 // %n - Assembler operand n
687 char *End;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000688 unsigned long n = strtoul(Start, &End, 10);
689 if (Start == End) {
690 // FIXME: This should be caught during Sema.
691 assert(0 && "Missing operand!");
692 } else if (n >= NumOperands) {
693 // FIXME: This should be caught during Sema.
694 assert(0 && "Operand number out of range!");
695 }
696
697 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000698 Start = End - 1;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000699 } else if (isalpha(EscapedChar)) {
700 char *End;
701
702 unsigned long n = strtoul(Start + 1, &End, 10);
703 if (Start == End) {
704 // FIXME: This should be caught during Sema.
705 assert(0 && "Missing operand!");
706 } else if (n >= NumOperands) {
707 // FIXME: This should be caught during Sema.
708 assert(0 && "Operand number out of range!");
709 }
710
711 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000712 Start = End - 1;
Anders Carlssonce179ab2008-11-09 18:54:14 +0000713 } else if (EscapedChar == '[') {
714 std::string SymbolicName;
715
716 Start++;
717
718 while (*Start && *Start != ']') {
719 SymbolicName += *Start;
720
721 Start++;
722 }
723
724 if (!Start) {
725 // FIXME: Should be caught by sema.
726 assert(0 && "Could not parse symbolic name");
727 }
728
729 assert(*Start == ']' && "Error parsing symbolic name");
730
731 int Index = -1;
732
733 // Check if this is an output operand.
734 for (unsigned i = 0; i < S.getNumOutputs(); i++) {
735 if (S.getOutputName(i) == SymbolicName) {
736 Index = i;
737 break;
738 }
739 }
740
741 if (Index == -1) {
742 for (unsigned i = 0; i < S.getNumInputs(); i++) {
743 if (S.getInputName(i) == SymbolicName) {
744 Index = S.getNumOutputs() + i;
745 }
746 }
747 }
748
749 assert(Index != -1 && "Did not find right operand!");
750
751 Result += '$' + llvm::utostr(Index);
752
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000753 } else {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000754 Failed = true;
755 return "";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000756 }
757 }
758 Start++;
759 }
760
761 return Result;
762}
763
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000764static std::string SimplifyConstraint(const char* Constraint,
765 TargetInfo &Target) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000766 std::string Result;
767
768 while (*Constraint) {
769 switch (*Constraint) {
770 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000771 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000772 break;
773 // Ignore these
774 case '*':
775 case '?':
776 case '!':
777 break;
778 case 'g':
779 Result += "imr";
780 break;
781 }
782
783 Constraint++;
784 }
785
786 return Result;
787}
788
789void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000790 bool Failed;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000791 std::string AsmString =
Anders Carlssonce179ab2008-11-09 18:54:14 +0000792 ConvertAsmString(S, Failed);
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000793
794 if (Failed) {
795 ErrorUnsupported(&S, "asm string");
796 return;
797 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000798
799 std::string Constraints;
800
801 llvm::Value *ResultAddr = 0;
802 const llvm::Type *ResultType = llvm::Type::VoidTy;
803
804 std::vector<const llvm::Type*> ArgTypes;
805 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000806
807 // Keep track of inout constraints.
808 std::string InOutConstraints;
809 std::vector<llvm::Value*> InOutArgs;
810 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000811
812 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
813 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
814 S.getOutputConstraint(i)->getByteLength());
815
816 TargetInfo::ConstraintInfo Info;
817 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
818 Info);
Chris Lattner3304e552008-10-12 00:31:50 +0000819 assert(result && "Failed to parse output constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000820
821 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000822 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000823
824 LValue Dest = EmitLValue(S.getOutputExpr(i));
825 const llvm::Type *DestValueType =
826 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
827
828 // If the first output operand is not a memory dest, we'll
829 // make it the return value.
830 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohmand79a7262008-05-22 22:12:56 +0000831 DestValueType->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000832 ResultAddr = Dest.getAddress();
833 ResultType = DestValueType;
834 Constraints += "=" + OutputConstraint;
835 } else {
836 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000837 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000838 if (i != 0)
839 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +0000840 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000841 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000842 }
843
844 if (Info & TargetInfo::CI_ReadWrite) {
845 // FIXME: This code should be shared with the code that handles inputs.
846 InOutConstraints += ',';
847
848 const Expr *InputExpr = S.getOutputExpr(i);
849 llvm::Value *Arg;
850 if ((Info & TargetInfo::CI_AllowsRegister) ||
851 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000852 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonf39a4212008-02-05 20:01:53 +0000853 Arg = EmitScalarExpr(InputExpr);
854 } else {
Chris Lattner62b72f62008-11-11 07:24:28 +0000855 ErrorUnsupported(&S,
856 "asm statement passing multiple-value types as inputs");
Anders Carlssonf39a4212008-02-05 20:01:53 +0000857 }
858 } else {
859 LValue Dest = EmitLValue(InputExpr);
860 Arg = Dest.getAddress();
861 InOutConstraints += '*';
862 }
863
864 InOutArgTypes.push_back(Arg->getType());
865 InOutArgs.push_back(Arg);
866 InOutConstraints += OutputConstraint;
867 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000868 }
869
870 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
871
872 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
873 const Expr *InputExpr = S.getInputExpr(i);
874
875 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
876 S.getInputConstraint(i)->getByteLength());
877
878 TargetInfo::ConstraintInfo Info;
879 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
Chris Lattner3304e552008-10-12 00:31:50 +0000880 NumConstraints, Info);
881 assert(result && "Failed to parse input constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000882
883 if (i != 0 || S.getNumOutputs() > 0)
884 Constraints += ',';
885
886 // Simplify the input constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000887 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000888
889 llvm::Value *Arg;
890
891 if ((Info & TargetInfo::CI_AllowsRegister) ||
892 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000893 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000894 Arg = EmitScalarExpr(InputExpr);
895 } else {
Chris Lattner62b72f62008-11-11 07:24:28 +0000896 ErrorUnsupported(&S,
897 "asm statement passing multiple-value types as inputs");
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000898 }
899 } else {
900 LValue Dest = EmitLValue(InputExpr);
901 Arg = Dest.getAddress();
902 Constraints += '*';
903 }
904
905 ArgTypes.push_back(Arg->getType());
906 Args.push_back(Arg);
907 Constraints += InputConstraint;
908 }
909
Anders Carlssonf39a4212008-02-05 20:01:53 +0000910 // Append the "input" part of inout constraints last.
911 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
912 ArgTypes.push_back(InOutArgTypes[i]);
913 Args.push_back(InOutArgs[i]);
914 }
915 Constraints += InOutConstraints;
916
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000917 // Clobbers
918 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
919 std::string Clobber(S.getClobber(i)->getStrData(),
920 S.getClobber(i)->getByteLength());
921
922 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
923
Anders Carlssonea041752008-02-06 00:11:32 +0000924 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000925 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +0000926
927 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000928 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +0000929 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000930 }
931
932 // Add machine specific clobbers
933 if (const char *C = Target.getClobbers()) {
934 if (!Constraints.empty())
935 Constraints += ',';
936 Constraints += C;
937 }
Anders Carlssonf39a4212008-02-05 20:01:53 +0000938
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000939 const llvm::FunctionType *FTy =
940 llvm::FunctionType::get(ResultType, ArgTypes, false);
941
942 llvm::InlineAsm *IA =
943 llvm::InlineAsm::get(FTy, AsmString, Constraints,
944 S.isVolatile() || S.getNumOutputs() == 0);
945 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
Eli Friedman1e692ac2008-06-13 23:01:12 +0000946 if (ResultAddr) // FIXME: volatility
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000947 Builder.CreateStore(Result, ResultAddr);
948}