xref: /llvm-project/clang/lib/CodeGen/CodeGenFunction.cpp (revision 8a01b79274be3a2128be030f1ef3180d26e7317c)
1 //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This coordinates the per-function state used while generating code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenFunction.h"
15 #include "CodeGenModule.h"
16 #include "CGDebugInfo.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/AST/APValue.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/Decl.h"
21 #include "llvm/Support/CFG.h"
22 using namespace clang;
23 using namespace CodeGen;
24 
25 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
26   : CGM(cgm), Target(CGM.getContext().Target), SwitchInsn(NULL),
27     CaseRangeBlock(NULL) {
28     LLVMIntTy = ConvertType(getContext().IntTy);
29     LLVMPointerWidth = Target.getPointerWidth(0);
30 }
31 
32 ASTContext &CodeGenFunction::getContext() const {
33   return CGM.getContext();
34 }
35 
36 
37 llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
38   llvm::BasicBlock *&BB = LabelMap[S];
39   if (BB) return BB;
40 
41   // Create, but don't insert, the new block.
42   return BB = createBasicBlock(S->getName());
43 }
44 
45 llvm::Constant *
46 CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
47   return cast<llvm::Constant>(LocalDeclMap[BVD]);
48 }
49 
50 llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD)
51 {
52   return LocalDeclMap[VD];
53 }
54 
55 const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
56   return CGM.getTypes().ConvertType(T);
57 }
58 
59 bool CodeGenFunction::isObjCPointerType(QualType T) {
60   // All Objective-C types are pointers.
61   return T->isObjCInterfaceType() ||
62     T->isObjCQualifiedInterfaceType() || T->isObjCQualifiedIdType();
63 }
64 
65 bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
66   return !isObjCPointerType(T) &&!T->isRealType() && !T->isPointerLikeType() &&
67     !T->isVoidType() && !T->isVectorType() && !T->isFunctionType();
68 }
69 
70 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
71   // Finish emission of indirect switches.
72   EmitIndirectSwitches();
73 
74   assert(BreakContinueStack.empty() &&
75          "mismatched push/pop in break/continue stack!");
76 
77   // Emit function epilog (to return). This has the nice side effect
78   // of also automatically handling code that falls off the end.
79   EmitBlock(ReturnBlock);
80 
81   // Emit debug descriptor for function end.
82   if (CGDebugInfo *DI = CGM.getDebugInfo()) {
83     DI->setLocation(EndLoc);
84     DI->EmitRegionEnd(CurFn, Builder);
85   }
86 
87   EmitFunctionEpilog(FnRetTy, ReturnValue);
88 
89   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
90   AllocaInsertPt->eraseFromParent();
91   AllocaInsertPt = 0;
92 }
93 
94 void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy,
95                                     llvm::Function *Fn,
96                                     const FunctionArgList &Args,
97                                     SourceLocation StartLoc) {
98   CurFuncDecl = D;
99   FnRetTy = RetTy;
100   CurFn = Fn;
101   assert(CurFn->isDeclaration() && "Function already has body?");
102 
103   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
104 
105   // Create a marker to make it easy to insert allocas into the entryblock
106   // later.  Don't create this with the builder, because we don't want it
107   // folded.
108   llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
109   AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt",
110                                          EntryBB);
111 
112   ReturnBlock = createBasicBlock("return");
113   ReturnValue = 0;
114   if (!RetTy->isVoidType())
115     ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
116 
117   Builder.SetInsertPoint(EntryBB);
118 
119   // Emit subprogram debug descriptor.
120   // FIXME: The cast here is a huge hack.
121   if (CGDebugInfo *DI = CGM.getDebugInfo()) {
122     DI->setLocation(StartLoc);
123     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
124       DI->EmitFunctionStart(FD->getIdentifier()->getName(),
125                             RetTy, CurFn, Builder);
126     } else {
127       // Just use LLVM function name.
128       DI->EmitFunctionStart(Fn->getName().c_str(),
129                             RetTy, CurFn, Builder);
130     }
131   }
132 
133   EmitFunctionProlog(CurFn, FnRetTy, Args);
134 }
135 
136 void CodeGenFunction::GenerateCode(const FunctionDecl *FD,
137                                    llvm::Function *Fn) {
138   FunctionArgList Args;
139   if (FD->getNumParams()) {
140     const FunctionTypeProto* FProto = FD->getType()->getAsFunctionTypeProto();
141     assert(FProto && "Function def must have prototype!");
142 
143     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
144       Args.push_back(std::make_pair(FD->getParamDecl(i),
145                                     FProto->getArgType(i)));
146   }
147 
148   StartFunction(FD, FD->getResultType(), Fn, Args,
149                 cast<CompoundStmt>(FD->getBody())->getLBracLoc());
150 
151   EmitStmt(FD->getBody());
152 
153   const CompoundStmt *S = dyn_cast<CompoundStmt>(FD->getBody());
154   if (S) {
155     FinishFunction(S->getRBracLoc());
156   } else {
157     FinishFunction();
158   }
159 }
160 
161 /// ContainsLabel - Return true if the statement contains a label in it.  If
162 /// this statement is not executed normally, it not containing a label means
163 /// that we can just remove the code.
164 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
165   // Null statement, not a label!
166   if (S == 0) return false;
167 
168   // If this is a label, we have to emit the code, consider something like:
169   // if (0) {  ...  foo:  bar(); }  goto foo;
170   if (isa<LabelStmt>(S))
171     return true;
172 
173   // If this is a case/default statement, and we haven't seen a switch, we have
174   // to emit the code.
175   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
176     return true;
177 
178   // If this is a switch statement, we want to ignore cases below it.
179   if (isa<SwitchStmt>(S))
180     IgnoreCaseStmts = true;
181 
182   // Scan subexpressions for verboten labels.
183   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
184        I != E; ++I)
185     if (ContainsLabel(*I, IgnoreCaseStmts))
186       return true;
187 
188   return false;
189 }
190 
191 
192 /// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
193 /// a constant, or if it does but contains a label, return 0.  If it constant
194 /// folds to 'true' and does not contain a label, return 1, if it constant folds
195 /// to 'false' and does not contain a label, return -1.
196 int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
197   // FIXME: Rename and handle conversion of other evaluatable things
198   // to bool.
199   Expr::EvalResult Result;
200   if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
201       Result.HasSideEffects)
202     return 0;  // Not foldable, not integer or not fully evaluatable.
203 
204   if (CodeGenFunction::ContainsLabel(Cond))
205     return 0;  // Contains a label.
206 
207   return Result.Val.getInt().getBoolValue() ? 1 : -1;
208 }
209 
210 
211 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
212 /// statement) to the specified blocks.  Based on the condition, this might try
213 /// to simplify the codegen of the conditional based on the branch.
214 ///
215 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
216                                            llvm::BasicBlock *TrueBlock,
217                                            llvm::BasicBlock *FalseBlock) {
218   if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
219     return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
220 
221   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
222     // Handle X && Y in a condition.
223     if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
224       // If we have "1 && X", simplify the code.  "0 && X" would have constant
225       // folded if the case was simple enough.
226       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
227         // br(1 && X) -> br(X).
228         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
229       }
230 
231       // If we have "X && 1", simplify the code to use an uncond branch.
232       // "X && 0" would have been constant folded to 0.
233       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
234         // br(X && 1) -> br(X).
235         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
236       }
237 
238       // Emit the LHS as a conditional.  If the LHS conditional is false, we
239       // want to jump to the FalseBlock.
240       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
241       EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
242       EmitBlock(LHSTrue);
243 
244       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
245       return;
246     } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
247       // If we have "0 || X", simplify the code.  "1 || X" would have constant
248       // folded if the case was simple enough.
249       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
250         // br(0 || X) -> br(X).
251         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
252       }
253 
254       // If we have "X || 0", simplify the code to use an uncond branch.
255       // "X || 1" would have been constant folded to 1.
256       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
257         // br(X || 0) -> br(X).
258         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
259       }
260 
261       // Emit the LHS as a conditional.  If the LHS conditional is true, we
262       // want to jump to the TrueBlock.
263       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
264       EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
265       EmitBlock(LHSFalse);
266 
267       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
268       return;
269     }
270   }
271 
272   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
273     // br(!x, t, f) -> br(x, f, t)
274     if (CondUOp->getOpcode() == UnaryOperator::LNot)
275       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
276   }
277 
278   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
279     // Handle ?: operator.
280 
281     // Just ignore GNU ?: extension.
282     if (CondOp->getLHS()) {
283       // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
284       llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
285       llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
286       EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
287       EmitBlock(LHSBlock);
288       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
289       EmitBlock(RHSBlock);
290       EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
291       return;
292     }
293   }
294 
295   // Emit the code with the fully general case.
296   llvm::Value *CondV = EvaluateExprAsBool(Cond);
297   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
298 }
299 
300 /// getCGRecordLayout - Return record layout info.
301 const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
302                                                          QualType Ty) {
303   const RecordType *RTy = Ty->getAsRecordType();
304   assert (RTy && "Unexpected type. RecordType expected here.");
305 
306   return CGT.getCGRecordLayout(RTy->getDecl());
307 }
308 
309 /// ErrorUnsupported - Print out an error that codegen doesn't support the
310 /// specified stmt yet.
311 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
312                                        bool OmitOnError) {
313   CGM.ErrorUnsupported(S, Type, OmitOnError);
314 }
315 
316 unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
317   // Use LabelIDs.size() as the new ID if one hasn't been assigned.
318   return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second;
319 }
320 
321 void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty)
322 {
323   const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
324   if (DestPtr->getType() != BP)
325     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
326 
327   // Get size and alignment info for this aggregate.
328   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
329 
330   // FIXME: Handle variable sized types.
331   const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
332 
333   Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
334                       llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty),
335                       // TypeInfo.first describes size in bits.
336                       llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
337                       llvm::ConstantInt::get(llvm::Type::Int32Ty,
338                                              TypeInfo.second/8));
339 }
340 
341 void CodeGenFunction::EmitIndirectSwitches() {
342   llvm::BasicBlock *Default;
343 
344   if (IndirectSwitches.empty())
345     return;
346 
347   if (!LabelIDs.empty()) {
348     Default = getBasicBlockForLabel(LabelIDs.begin()->first);
349   } else {
350     // No possible targets for indirect goto, just emit an infinite
351     // loop.
352     Default = createBasicBlock("indirectgoto.loop", CurFn);
353     llvm::BranchInst::Create(Default, Default);
354   }
355 
356   for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
357          e = IndirectSwitches.end(); i != e; ++i) {
358     llvm::SwitchInst *I = *i;
359 
360     I->setSuccessor(0, Default);
361     for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
362            LE = LabelIDs.end(); LI != LE; ++LI) {
363       I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty,
364                                         LI->second),
365                  getBasicBlockForLabel(LI->first));
366     }
367   }
368 }
369 
370 llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty)
371 {
372   // FIXME: This entire method is hardcoded for 32-bit X86.
373 
374   const char *TargetPrefix = getContext().Target.getTargetPrefix();
375 
376   if (strcmp(TargetPrefix, "x86") != 0 ||
377       getContext().Target.getPointerWidth(0) != 32)
378     return 0;
379 
380   const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
381   const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
382 
383   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
384                                                        "ap");
385   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
386   llvm::Value *AddrTyped =
387     Builder.CreateBitCast(Addr,
388                           llvm::PointerType::getUnqual(ConvertType(Ty)));
389 
390   uint64_t SizeInBytes = getContext().getTypeSize(Ty) / 8;
391   const unsigned ArgumentSizeInBytes = 4;
392   if (SizeInBytes < ArgumentSizeInBytes)
393     SizeInBytes = ArgumentSizeInBytes;
394 
395   llvm::Value *NextAddr =
396     Builder.CreateGEP(Addr,
397                       llvm::ConstantInt::get(llvm::Type::Int32Ty, SizeInBytes),
398                       "ap.next");
399   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
400 
401   return AddrTyped;
402 }
403 
404 
405 llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT)
406 {
407   llvm::Value *&SizeEntry = VLASizeMap[VAT];
408 
409   assert(SizeEntry && "Did not emit size for type");
410   return SizeEntry;
411 }
412 
413 llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty)
414 {
415   assert(Ty->isVariablyModifiedType() &&
416          "Must pass variably modified type to EmitVLASizes!");
417 
418   if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
419     llvm::Value *&SizeEntry = VLASizeMap[VAT];
420 
421     assert(!SizeEntry && "Must not emit the same VLA size more than once!");
422 
423     // Get the element size;
424     llvm::Value *ElemSize;
425 
426     QualType ElemTy = VAT->getElementType();
427 
428     if (ElemTy->isVariableArrayType())
429       ElemSize = EmitVLASize(ElemTy);
430     else {
431       // FIXME: We use Int32Ty here because the alloca instruction takes a
432       // 32-bit integer. What should we do about overflow?
433       ElemSize = llvm::ConstantInt::get(llvm::Type::Int32Ty,
434                                         getContext().getTypeSize(ElemTy) / 8);
435     }
436 
437     llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
438 
439     SizeEntry = Builder.CreateMul(ElemSize, NumElements);
440 
441     return SizeEntry;
442   } else if (const PointerType *PT = Ty->getAsPointerType())
443     EmitVLASize(PT->getPointeeType());
444   else {
445     assert(0 && "unknown VM type!");
446   }
447 
448   return 0;
449 }
450