CodeGenFunction.cpp 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070
  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. #include "CodeGenFunction.h"
  14. #include "CodeGenModule.h"
  15. #include "CGCXXABI.h"
  16. #include "CGDebugInfo.h"
  17. #include "CGException.h"
  18. #include "clang/Basic/TargetInfo.h"
  19. #include "clang/AST/APValue.h"
  20. #include "clang/AST/ASTContext.h"
  21. #include "clang/AST/Decl.h"
  22. #include "clang/AST/DeclCXX.h"
  23. #include "clang/AST/StmtCXX.h"
  24. #include "clang/Frontend/CodeGenOptions.h"
  25. #include "llvm/Target/TargetData.h"
  26. #include "llvm/Intrinsics.h"
  27. using namespace clang;
  28. using namespace CodeGen;
  29. CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
  30. : CodeGenTypeCache(cgm), CGM(cgm),
  31. Target(CGM.getContext().getTargetInfo()), Builder(cgm.getModule().getContext()),
  32. AutoreleaseResult(false), BlockInfo(0), BlockPointer(0),
  33. NormalCleanupDest(0), NextCleanupDestIndex(1),
  34. EHResumeBlock(0), ExceptionSlot(0), EHSelectorSlot(0),
  35. DebugInfo(0), DisableDebugInfo(false), DidCallStackSave(false),
  36. IndirectBranch(0), SwitchInsn(0), CaseRangeBlock(0), UnreachableBlock(0),
  37. CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0),
  38. OutermostConditional(0), TerminateLandingPad(0), TerminateHandler(0),
  39. TrapBB(0) {
  40. CatchUndefined = getContext().getLangOptions().CatchUndefined;
  41. CGM.getCXXABI().getMangleContext().startNewFunction();
  42. }
  43. llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
  44. return CGM.getTypes().ConvertTypeForMem(T);
  45. }
  46. llvm::Type *CodeGenFunction::ConvertType(QualType T) {
  47. return CGM.getTypes().ConvertType(T);
  48. }
  49. bool CodeGenFunction::hasAggregateLLVMType(QualType type) {
  50. switch (type.getCanonicalType()->getTypeClass()) {
  51. #define TYPE(name, parent)
  52. #define ABSTRACT_TYPE(name, parent)
  53. #define NON_CANONICAL_TYPE(name, parent) case Type::name:
  54. #define DEPENDENT_TYPE(name, parent) case Type::name:
  55. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
  56. #include "clang/AST/TypeNodes.def"
  57. llvm_unreachable("non-canonical or dependent type in IR-generation");
  58. case Type::Builtin:
  59. case Type::Pointer:
  60. case Type::BlockPointer:
  61. case Type::LValueReference:
  62. case Type::RValueReference:
  63. case Type::MemberPointer:
  64. case Type::Vector:
  65. case Type::ExtVector:
  66. case Type::FunctionProto:
  67. case Type::FunctionNoProto:
  68. case Type::Enum:
  69. case Type::ObjCObjectPointer:
  70. return false;
  71. // Complexes, arrays, records, and Objective-C objects.
  72. case Type::Complex:
  73. case Type::ConstantArray:
  74. case Type::IncompleteArray:
  75. case Type::VariableArray:
  76. case Type::Record:
  77. case Type::ObjCObject:
  78. case Type::ObjCInterface:
  79. return true;
  80. }
  81. llvm_unreachable("unknown type kind!");
  82. }
  83. void CodeGenFunction::EmitReturnBlock() {
  84. // For cleanliness, we try to avoid emitting the return block for
  85. // simple cases.
  86. llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
  87. if (CurBB) {
  88. assert(!CurBB->getTerminator() && "Unexpected terminated block.");
  89. // We have a valid insert point, reuse it if it is empty or there are no
  90. // explicit jumps to the return block.
  91. if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
  92. ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
  93. delete ReturnBlock.getBlock();
  94. } else
  95. EmitBlock(ReturnBlock.getBlock());
  96. return;
  97. }
  98. // Otherwise, if the return block is the target of a single direct
  99. // branch then we can just put the code in that block instead. This
  100. // cleans up functions which started with a unified return block.
  101. if (ReturnBlock.getBlock()->hasOneUse()) {
  102. llvm::BranchInst *BI =
  103. dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->use_begin());
  104. if (BI && BI->isUnconditional() &&
  105. BI->getSuccessor(0) == ReturnBlock.getBlock()) {
  106. // Reset insertion point, including debug location, and delete the branch.
  107. Builder.SetCurrentDebugLocation(BI->getDebugLoc());
  108. Builder.SetInsertPoint(BI->getParent());
  109. BI->eraseFromParent();
  110. delete ReturnBlock.getBlock();
  111. return;
  112. }
  113. }
  114. // FIXME: We are at an unreachable point, there is no reason to emit the block
  115. // unless it has uses. However, we still need a place to put the debug
  116. // region.end for now.
  117. EmitBlock(ReturnBlock.getBlock());
  118. }
  119. static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
  120. if (!BB) return;
  121. if (!BB->use_empty())
  122. return CGF.CurFn->getBasicBlockList().push_back(BB);
  123. delete BB;
  124. }
  125. void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
  126. assert(BreakContinueStack.empty() &&
  127. "mismatched push/pop in break/continue stack!");
  128. // Pop any cleanups that might have been associated with the
  129. // parameters. Do this in whatever block we're currently in; it's
  130. // important to do this before we enter the return block or return
  131. // edges will be *really* confused.
  132. if (EHStack.stable_begin() != PrologueCleanupDepth)
  133. PopCleanupBlocks(PrologueCleanupDepth);
  134. // Emit function epilog (to return).
  135. EmitReturnBlock();
  136. if (ShouldInstrumentFunction())
  137. EmitFunctionInstrumentation("__cyg_profile_func_exit");
  138. // Emit debug descriptor for function end.
  139. if (CGDebugInfo *DI = getDebugInfo()) {
  140. DI->setLocation(EndLoc);
  141. DI->EmitFunctionEnd(Builder);
  142. }
  143. EmitFunctionEpilog(*CurFnInfo);
  144. EmitEndEHSpec(CurCodeDecl);
  145. assert(EHStack.empty() &&
  146. "did not remove all scopes from cleanup stack!");
  147. // If someone did an indirect goto, emit the indirect goto block at the end of
  148. // the function.
  149. if (IndirectBranch) {
  150. EmitBlock(IndirectBranch->getParent());
  151. Builder.ClearInsertionPoint();
  152. }
  153. // Remove the AllocaInsertPt instruction, which is just a convenience for us.
  154. llvm::Instruction *Ptr = AllocaInsertPt;
  155. AllocaInsertPt = 0;
  156. Ptr->eraseFromParent();
  157. // If someone took the address of a label but never did an indirect goto, we
  158. // made a zero entry PHI node, which is illegal, zap it now.
  159. if (IndirectBranch) {
  160. llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
  161. if (PN->getNumIncomingValues() == 0) {
  162. PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
  163. PN->eraseFromParent();
  164. }
  165. }
  166. EmitIfUsed(*this, EHResumeBlock);
  167. EmitIfUsed(*this, TerminateLandingPad);
  168. EmitIfUsed(*this, TerminateHandler);
  169. EmitIfUsed(*this, UnreachableBlock);
  170. if (CGM.getCodeGenOpts().EmitDeclMetadata)
  171. EmitDeclMetadata();
  172. }
  173. /// ShouldInstrumentFunction - Return true if the current function should be
  174. /// instrumented with __cyg_profile_func_* calls
  175. bool CodeGenFunction::ShouldInstrumentFunction() {
  176. if (!CGM.getCodeGenOpts().InstrumentFunctions)
  177. return false;
  178. if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
  179. return false;
  180. return true;
  181. }
  182. /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
  183. /// instrumentation function with the current function and the call site, if
  184. /// function instrumentation is enabled.
  185. void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
  186. // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
  187. llvm::PointerType *PointerTy = Int8PtrTy;
  188. llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy };
  189. llvm::FunctionType *FunctionTy =
  190. llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
  191. ProfileFuncArgs, false);
  192. llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
  193. llvm::CallInst *CallSite = Builder.CreateCall(
  194. CGM.getIntrinsic(llvm::Intrinsic::returnaddress),
  195. llvm::ConstantInt::get(Int32Ty, 0),
  196. "callsite");
  197. Builder.CreateCall2(F,
  198. llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
  199. CallSite);
  200. }
  201. void CodeGenFunction::EmitMCountInstrumentation() {
  202. llvm::FunctionType *FTy =
  203. llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()), false);
  204. llvm::Constant *MCountFn = CGM.CreateRuntimeFunction(FTy,
  205. Target.getMCountName());
  206. Builder.CreateCall(MCountFn);
  207. }
  208. void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
  209. llvm::Function *Fn,
  210. const CGFunctionInfo &FnInfo,
  211. const FunctionArgList &Args,
  212. SourceLocation StartLoc) {
  213. const Decl *D = GD.getDecl();
  214. DidCallStackSave = false;
  215. CurCodeDecl = CurFuncDecl = D;
  216. FnRetTy = RetTy;
  217. CurFn = Fn;
  218. CurFnInfo = &FnInfo;
  219. assert(CurFn->isDeclaration() && "Function already has body?");
  220. // Pass inline keyword to optimizer if it appears explicitly on any
  221. // declaration.
  222. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  223. for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
  224. RE = FD->redecls_end(); RI != RE; ++RI)
  225. if (RI->isInlineSpecified()) {
  226. Fn->addFnAttr(llvm::Attribute::InlineHint);
  227. break;
  228. }
  229. if (getContext().getLangOptions().OpenCL) {
  230. // Add metadata for a kernel function.
  231. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  232. if (FD->hasAttr<OpenCLKernelAttr>()) {
  233. llvm::LLVMContext &Context = getLLVMContext();
  234. llvm::NamedMDNode *OpenCLMetadata =
  235. CGM.getModule().getOrInsertNamedMetadata("opencl.kernels");
  236. llvm::Value *Op = Fn;
  237. OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Op));
  238. }
  239. }
  240. llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
  241. // Create a marker to make it easy to insert allocas into the entryblock
  242. // later. Don't create this with the builder, because we don't want it
  243. // folded.
  244. llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
  245. AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
  246. if (Builder.isNamePreserving())
  247. AllocaInsertPt->setName("allocapt");
  248. ReturnBlock = getJumpDestInCurrentScope("return");
  249. Builder.SetInsertPoint(EntryBB);
  250. // Emit subprogram debug descriptor.
  251. if (CGDebugInfo *DI = getDebugInfo()) {
  252. // FIXME: what is going on here and why does it ignore all these
  253. // interesting type properties?
  254. QualType FnType =
  255. getContext().getFunctionType(RetTy, 0, 0,
  256. FunctionProtoType::ExtProtoInfo());
  257. DI->setLocation(StartLoc);
  258. DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
  259. }
  260. if (ShouldInstrumentFunction())
  261. EmitFunctionInstrumentation("__cyg_profile_func_enter");
  262. if (CGM.getCodeGenOpts().InstrumentForProfiling)
  263. EmitMCountInstrumentation();
  264. if (RetTy->isVoidType()) {
  265. // Void type; nothing to return.
  266. ReturnValue = 0;
  267. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
  268. hasAggregateLLVMType(CurFnInfo->getReturnType())) {
  269. // Indirect aggregate return; emit returned value directly into sret slot.
  270. // This reduces code size, and affects correctness in C++.
  271. ReturnValue = CurFn->arg_begin();
  272. } else {
  273. ReturnValue = CreateIRTemp(RetTy, "retval");
  274. // Tell the epilog emitter to autorelease the result. We do this
  275. // now so that various specialized functions can suppress it
  276. // during their IR-generation.
  277. if (getLangOptions().ObjCAutoRefCount &&
  278. !CurFnInfo->isReturnsRetained() &&
  279. RetTy->isObjCRetainableType())
  280. AutoreleaseResult = true;
  281. }
  282. EmitStartEHSpec(CurCodeDecl);
  283. PrologueCleanupDepth = EHStack.stable_begin();
  284. EmitFunctionProlog(*CurFnInfo, CurFn, Args);
  285. if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance())
  286. CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
  287. // If any of the arguments have a variably modified type, make sure to
  288. // emit the type size.
  289. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
  290. i != e; ++i) {
  291. QualType Ty = (*i)->getType();
  292. if (Ty->isVariablyModifiedType())
  293. EmitVariablyModifiedType(Ty);
  294. }
  295. }
  296. void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
  297. const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
  298. assert(FD->getBody());
  299. EmitStmt(FD->getBody());
  300. }
  301. /// Tries to mark the given function nounwind based on the
  302. /// non-existence of any throwing calls within it. We believe this is
  303. /// lightweight enough to do at -O0.
  304. static void TryMarkNoThrow(llvm::Function *F) {
  305. // LLVM treats 'nounwind' on a function as part of the type, so we
  306. // can't do this on functions that can be overwritten.
  307. if (F->mayBeOverridden()) return;
  308. for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
  309. for (llvm::BasicBlock::iterator
  310. BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
  311. if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI)) {
  312. if (!Call->doesNotThrow())
  313. return;
  314. } else if (isa<llvm::ResumeInst>(&*BI)) {
  315. return;
  316. }
  317. F->setDoesNotThrow(true);
  318. }
  319. void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
  320. const CGFunctionInfo &FnInfo) {
  321. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  322. // Check if we should generate debug info for this function.
  323. if (CGM.getModuleDebugInfo() && !FD->hasAttr<NoDebugAttr>())
  324. DebugInfo = CGM.getModuleDebugInfo();
  325. FunctionArgList Args;
  326. QualType ResTy = FD->getResultType();
  327. CurGD = GD;
  328. if (isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isInstance())
  329. CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResTy, Args);
  330. if (FD->getNumParams())
  331. for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
  332. Args.push_back(FD->getParamDecl(i));
  333. SourceRange BodyRange;
  334. if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
  335. // Emit the standard function prologue.
  336. StartFunction(GD, ResTy, Fn, FnInfo, Args, BodyRange.getBegin());
  337. // Generate the body of the function.
  338. if (isa<CXXDestructorDecl>(FD))
  339. EmitDestructorBody(Args);
  340. else if (isa<CXXConstructorDecl>(FD))
  341. EmitConstructorBody(Args);
  342. else
  343. EmitFunctionBody(Args);
  344. // Emit the standard function epilogue.
  345. FinishFunction(BodyRange.getEnd());
  346. // If we haven't marked the function nothrow through other means, do
  347. // a quick pass now to see if we can.
  348. if (!CurFn->doesNotThrow())
  349. TryMarkNoThrow(CurFn);
  350. }
  351. /// ContainsLabel - Return true if the statement contains a label in it. If
  352. /// this statement is not executed normally, it not containing a label means
  353. /// that we can just remove the code.
  354. bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
  355. // Null statement, not a label!
  356. if (S == 0) return false;
  357. // If this is a label, we have to emit the code, consider something like:
  358. // if (0) { ... foo: bar(); } goto foo;
  359. //
  360. // TODO: If anyone cared, we could track __label__'s, since we know that you
  361. // can't jump to one from outside their declared region.
  362. if (isa<LabelStmt>(S))
  363. return true;
  364. // If this is a case/default statement, and we haven't seen a switch, we have
  365. // to emit the code.
  366. if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
  367. return true;
  368. // If this is a switch statement, we want to ignore cases below it.
  369. if (isa<SwitchStmt>(S))
  370. IgnoreCaseStmts = true;
  371. // Scan subexpressions for verboten labels.
  372. for (Stmt::const_child_range I = S->children(); I; ++I)
  373. if (ContainsLabel(*I, IgnoreCaseStmts))
  374. return true;
  375. return false;
  376. }
  377. /// containsBreak - Return true if the statement contains a break out of it.
  378. /// If the statement (recursively) contains a switch or loop with a break
  379. /// inside of it, this is fine.
  380. bool CodeGenFunction::containsBreak(const Stmt *S) {
  381. // Null statement, not a label!
  382. if (S == 0) return false;
  383. // If this is a switch or loop that defines its own break scope, then we can
  384. // include it and anything inside of it.
  385. if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
  386. isa<ForStmt>(S))
  387. return false;
  388. if (isa<BreakStmt>(S))
  389. return true;
  390. // Scan subexpressions for verboten breaks.
  391. for (Stmt::const_child_range I = S->children(); I; ++I)
  392. if (containsBreak(*I))
  393. return true;
  394. return false;
  395. }
  396. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  397. /// to a constant, or if it does but contains a label, return false. If it
  398. /// constant folds return true and set the boolean result in Result.
  399. bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
  400. bool &ResultBool) {
  401. llvm::APInt ResultInt;
  402. if (!ConstantFoldsToSimpleInteger(Cond, ResultInt))
  403. return false;
  404. ResultBool = ResultInt.getBoolValue();
  405. return true;
  406. }
  407. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  408. /// to a constant, or if it does but contains a label, return false. If it
  409. /// constant folds return true and set the folded value.
  410. bool CodeGenFunction::
  411. ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APInt &ResultInt) {
  412. // FIXME: Rename and handle conversion of other evaluatable things
  413. // to bool.
  414. Expr::EvalResult Result;
  415. if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
  416. Result.HasSideEffects)
  417. return false; // Not foldable, not integer or not fully evaluatable.
  418. if (CodeGenFunction::ContainsLabel(Cond))
  419. return false; // Contains a label.
  420. ResultInt = Result.Val.getInt();
  421. return true;
  422. }
  423. /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
  424. /// statement) to the specified blocks. Based on the condition, this might try
  425. /// to simplify the codegen of the conditional based on the branch.
  426. ///
  427. void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
  428. llvm::BasicBlock *TrueBlock,
  429. llvm::BasicBlock *FalseBlock) {
  430. Cond = Cond->IgnoreParens();
  431. if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
  432. // Handle X && Y in a condition.
  433. if (CondBOp->getOpcode() == BO_LAnd) {
  434. // If we have "1 && X", simplify the code. "0 && X" would have constant
  435. // folded if the case was simple enough.
  436. bool ConstantBool = false;
  437. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  438. ConstantBool) {
  439. // br(1 && X) -> br(X).
  440. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
  441. }
  442. // If we have "X && 1", simplify the code to use an uncond branch.
  443. // "X && 0" would have been constant folded to 0.
  444. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  445. ConstantBool) {
  446. // br(X && 1) -> br(X).
  447. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
  448. }
  449. // Emit the LHS as a conditional. If the LHS conditional is false, we
  450. // want to jump to the FalseBlock.
  451. llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
  452. ConditionalEvaluation eval(*this);
  453. EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
  454. EmitBlock(LHSTrue);
  455. // Any temporaries created here are conditional.
  456. eval.begin(*this);
  457. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
  458. eval.end(*this);
  459. return;
  460. }
  461. if (CondBOp->getOpcode() == BO_LOr) {
  462. // If we have "0 || X", simplify the code. "1 || X" would have constant
  463. // folded if the case was simple enough.
  464. bool ConstantBool = false;
  465. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  466. !ConstantBool) {
  467. // br(0 || X) -> br(X).
  468. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
  469. }
  470. // If we have "X || 0", simplify the code to use an uncond branch.
  471. // "X || 1" would have been constant folded to 1.
  472. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  473. !ConstantBool) {
  474. // br(X || 0) -> br(X).
  475. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
  476. }
  477. // Emit the LHS as a conditional. If the LHS conditional is true, we
  478. // want to jump to the TrueBlock.
  479. llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
  480. ConditionalEvaluation eval(*this);
  481. EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
  482. EmitBlock(LHSFalse);
  483. // Any temporaries created here are conditional.
  484. eval.begin(*this);
  485. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
  486. eval.end(*this);
  487. return;
  488. }
  489. }
  490. if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
  491. // br(!x, t, f) -> br(x, f, t)
  492. if (CondUOp->getOpcode() == UO_LNot)
  493. return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
  494. }
  495. if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
  496. // Handle ?: operator.
  497. // Just ignore GNU ?: extension.
  498. if (CondOp->getLHS()) {
  499. // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
  500. llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
  501. llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
  502. ConditionalEvaluation cond(*this);
  503. EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
  504. cond.begin(*this);
  505. EmitBlock(LHSBlock);
  506. EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
  507. cond.end(*this);
  508. cond.begin(*this);
  509. EmitBlock(RHSBlock);
  510. EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
  511. cond.end(*this);
  512. return;
  513. }
  514. }
  515. // Emit the code with the fully general case.
  516. llvm::Value *CondV = EvaluateExprAsBool(Cond);
  517. Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
  518. }
  519. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  520. /// specified stmt yet.
  521. void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
  522. bool OmitOnError) {
  523. CGM.ErrorUnsupported(S, Type, OmitOnError);
  524. }
  525. /// emitNonZeroVLAInit - Emit the "zero" initialization of a
  526. /// variable-length array whose elements have a non-zero bit-pattern.
  527. ///
  528. /// \param src - a char* pointing to the bit-pattern for a single
  529. /// base element of the array
  530. /// \param sizeInChars - the total size of the VLA, in chars
  531. /// \param align - the total alignment of the VLA
  532. static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
  533. llvm::Value *dest, llvm::Value *src,
  534. llvm::Value *sizeInChars) {
  535. std::pair<CharUnits,CharUnits> baseSizeAndAlign
  536. = CGF.getContext().getTypeInfoInChars(baseType);
  537. CGBuilderTy &Builder = CGF.Builder;
  538. llvm::Value *baseSizeInChars
  539. = llvm::ConstantInt::get(CGF.IntPtrTy, baseSizeAndAlign.first.getQuantity());
  540. llvm::Type *i8p = Builder.getInt8PtrTy();
  541. llvm::Value *begin = Builder.CreateBitCast(dest, i8p, "vla.begin");
  542. llvm::Value *end = Builder.CreateInBoundsGEP(dest, sizeInChars, "vla.end");
  543. llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
  544. llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
  545. llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
  546. // Make a loop over the VLA. C99 guarantees that the VLA element
  547. // count must be nonzero.
  548. CGF.EmitBlock(loopBB);
  549. llvm::PHINode *cur = Builder.CreatePHI(i8p, 2, "vla.cur");
  550. cur->addIncoming(begin, originBB);
  551. // memcpy the individual element bit-pattern.
  552. Builder.CreateMemCpy(cur, src, baseSizeInChars,
  553. baseSizeAndAlign.second.getQuantity(),
  554. /*volatile*/ false);
  555. // Go to the next element.
  556. llvm::Value *next = Builder.CreateConstInBoundsGEP1_32(cur, 1, "vla.next");
  557. // Leave if that's the end of the VLA.
  558. llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
  559. Builder.CreateCondBr(done, contBB, loopBB);
  560. cur->addIncoming(next, loopBB);
  561. CGF.EmitBlock(contBB);
  562. }
  563. void
  564. CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
  565. // Ignore empty classes in C++.
  566. if (getContext().getLangOptions().CPlusPlus) {
  567. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  568. if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
  569. return;
  570. }
  571. }
  572. // Cast the dest ptr to the appropriate i8 pointer type.
  573. unsigned DestAS =
  574. cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace();
  575. llvm::Type *BP = Builder.getInt8PtrTy(DestAS);
  576. if (DestPtr->getType() != BP)
  577. DestPtr = Builder.CreateBitCast(DestPtr, BP);
  578. // Get size and alignment info for this aggregate.
  579. std::pair<CharUnits, CharUnits> TypeInfo =
  580. getContext().getTypeInfoInChars(Ty);
  581. CharUnits Size = TypeInfo.first;
  582. CharUnits Align = TypeInfo.second;
  583. llvm::Value *SizeVal;
  584. const VariableArrayType *vla;
  585. // Don't bother emitting a zero-byte memset.
  586. if (Size.isZero()) {
  587. // But note that getTypeInfo returns 0 for a VLA.
  588. if (const VariableArrayType *vlaType =
  589. dyn_cast_or_null<VariableArrayType>(
  590. getContext().getAsArrayType(Ty))) {
  591. QualType eltType;
  592. llvm::Value *numElts;
  593. llvm::tie(numElts, eltType) = getVLASize(vlaType);
  594. SizeVal = numElts;
  595. CharUnits eltSize = getContext().getTypeSizeInChars(eltType);
  596. if (!eltSize.isOne())
  597. SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
  598. vla = vlaType;
  599. } else {
  600. return;
  601. }
  602. } else {
  603. SizeVal = CGM.getSize(Size);
  604. vla = 0;
  605. }
  606. // If the type contains a pointer to data member we can't memset it to zero.
  607. // Instead, create a null constant and copy it to the destination.
  608. // TODO: there are other patterns besides zero that we can usefully memset,
  609. // like -1, which happens to be the pattern used by member-pointers.
  610. if (!CGM.getTypes().isZeroInitializable(Ty)) {
  611. // For a VLA, emit a single element, then splat that over the VLA.
  612. if (vla) Ty = getContext().getBaseElementType(vla);
  613. llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
  614. llvm::GlobalVariable *NullVariable =
  615. new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
  616. /*isConstant=*/true,
  617. llvm::GlobalVariable::PrivateLinkage,
  618. NullConstant, Twine());
  619. llvm::Value *SrcPtr =
  620. Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy());
  621. if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
  622. // Get and call the appropriate llvm.memcpy overload.
  623. Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity(), false);
  624. return;
  625. }
  626. // Otherwise, just memset the whole thing to zero. This is legal
  627. // because in LLVM, all default initializers (other than the ones we just
  628. // handled above) are guaranteed to have a bit pattern of all zeros.
  629. Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal,
  630. Align.getQuantity(), false);
  631. }
  632. llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
  633. // Make sure that there is a block for the indirect goto.
  634. if (IndirectBranch == 0)
  635. GetIndirectGotoBlock();
  636. llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
  637. // Make sure the indirect branch includes all of the address-taken blocks.
  638. IndirectBranch->addDestination(BB);
  639. return llvm::BlockAddress::get(CurFn, BB);
  640. }
  641. llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
  642. // If we already made the indirect branch for indirect goto, return its block.
  643. if (IndirectBranch) return IndirectBranch->getParent();
  644. CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
  645. // Create the PHI node that indirect gotos will add entries to.
  646. llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
  647. "indirect.goto.dest");
  648. // Create the indirect branch instruction.
  649. IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
  650. return IndirectBranch->getParent();
  651. }
  652. /// Computes the length of an array in elements, as well as the base
  653. /// element type and a properly-typed first element pointer.
  654. llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
  655. QualType &baseType,
  656. llvm::Value *&addr) {
  657. const ArrayType *arrayType = origArrayType;
  658. // If it's a VLA, we have to load the stored size. Note that
  659. // this is the size of the VLA in bytes, not its size in elements.
  660. llvm::Value *numVLAElements = 0;
  661. if (isa<VariableArrayType>(arrayType)) {
  662. numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first;
  663. // Walk into all VLAs. This doesn't require changes to addr,
  664. // which has type T* where T is the first non-VLA element type.
  665. do {
  666. QualType elementType = arrayType->getElementType();
  667. arrayType = getContext().getAsArrayType(elementType);
  668. // If we only have VLA components, 'addr' requires no adjustment.
  669. if (!arrayType) {
  670. baseType = elementType;
  671. return numVLAElements;
  672. }
  673. } while (isa<VariableArrayType>(arrayType));
  674. // We get out here only if we find a constant array type
  675. // inside the VLA.
  676. }
  677. // We have some number of constant-length arrays, so addr should
  678. // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
  679. // down to the first element of addr.
  680. SmallVector<llvm::Value*, 8> gepIndices;
  681. // GEP down to the array type.
  682. llvm::ConstantInt *zero = Builder.getInt32(0);
  683. gepIndices.push_back(zero);
  684. // It's more efficient to calculate the count from the LLVM
  685. // constant-length arrays than to re-evaluate the array bounds.
  686. uint64_t countFromCLAs = 1;
  687. llvm::ArrayType *llvmArrayType =
  688. cast<llvm::ArrayType>(
  689. cast<llvm::PointerType>(addr->getType())->getElementType());
  690. while (true) {
  691. assert(isa<ConstantArrayType>(arrayType));
  692. assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
  693. == llvmArrayType->getNumElements());
  694. gepIndices.push_back(zero);
  695. countFromCLAs *= llvmArrayType->getNumElements();
  696. llvmArrayType =
  697. dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
  698. if (!llvmArrayType) break;
  699. arrayType = getContext().getAsArrayType(arrayType->getElementType());
  700. assert(arrayType && "LLVM and Clang types are out-of-synch");
  701. }
  702. baseType = arrayType->getElementType();
  703. // Create the actual GEP.
  704. addr = Builder.CreateInBoundsGEP(addr, gepIndices, "array.begin");
  705. llvm::Value *numElements
  706. = llvm::ConstantInt::get(SizeTy, countFromCLAs);
  707. // If we had any VLA dimensions, factor them in.
  708. if (numVLAElements)
  709. numElements = Builder.CreateNUWMul(numVLAElements, numElements);
  710. return numElements;
  711. }
  712. std::pair<llvm::Value*, QualType>
  713. CodeGenFunction::getVLASize(QualType type) {
  714. const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
  715. assert(vla && "type was not a variable array type!");
  716. return getVLASize(vla);
  717. }
  718. std::pair<llvm::Value*, QualType>
  719. CodeGenFunction::getVLASize(const VariableArrayType *type) {
  720. // The number of elements so far; always size_t.
  721. llvm::Value *numElements = 0;
  722. QualType elementType;
  723. do {
  724. elementType = type->getElementType();
  725. llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
  726. assert(vlaSize && "no size for VLA!");
  727. assert(vlaSize->getType() == SizeTy);
  728. if (!numElements) {
  729. numElements = vlaSize;
  730. } else {
  731. // It's undefined behavior if this wraps around, so mark it that way.
  732. numElements = Builder.CreateNUWMul(numElements, vlaSize);
  733. }
  734. } while ((type = getContext().getAsVariableArrayType(elementType)));
  735. return std::pair<llvm::Value*,QualType>(numElements, elementType);
  736. }
  737. void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
  738. assert(type->isVariablyModifiedType() &&
  739. "Must pass variably modified type to EmitVLASizes!");
  740. EnsureInsertPoint();
  741. // We're going to walk down into the type and look for VLA
  742. // expressions.
  743. type = type.getCanonicalType();
  744. do {
  745. assert(type->isVariablyModifiedType());
  746. const Type *ty = type.getTypePtr();
  747. switch (ty->getTypeClass()) {
  748. #define TYPE(Class, Base)
  749. #define ABSTRACT_TYPE(Class, Base)
  750. #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
  751. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  752. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
  753. #include "clang/AST/TypeNodes.def"
  754. llvm_unreachable("unexpected dependent or non-canonical type!");
  755. // These types are never variably-modified.
  756. case Type::Builtin:
  757. case Type::Complex:
  758. case Type::Vector:
  759. case Type::ExtVector:
  760. case Type::Record:
  761. case Type::Enum:
  762. case Type::ObjCObject:
  763. case Type::ObjCInterface:
  764. case Type::ObjCObjectPointer:
  765. llvm_unreachable("type class is never variably-modified!");
  766. case Type::Pointer:
  767. type = cast<PointerType>(ty)->getPointeeType();
  768. break;
  769. case Type::BlockPointer:
  770. type = cast<BlockPointerType>(ty)->getPointeeType();
  771. break;
  772. case Type::LValueReference:
  773. case Type::RValueReference:
  774. type = cast<ReferenceType>(ty)->getPointeeType();
  775. break;
  776. case Type::MemberPointer:
  777. type = cast<MemberPointerType>(ty)->getPointeeType();
  778. break;
  779. case Type::ConstantArray:
  780. case Type::IncompleteArray:
  781. // Losing element qualification here is fine.
  782. type = cast<ArrayType>(ty)->getElementType();
  783. break;
  784. case Type::VariableArray: {
  785. // Losing element qualification here is fine.
  786. const VariableArrayType *vat = cast<VariableArrayType>(ty);
  787. // Unknown size indication requires no size computation.
  788. // Otherwise, evaluate and record it.
  789. if (const Expr *size = vat->getSizeExpr()) {
  790. // It's possible that we might have emitted this already,
  791. // e.g. with a typedef and a pointer to it.
  792. llvm::Value *&entry = VLASizeMap[size];
  793. if (!entry) {
  794. // Always zexting here would be wrong if it weren't
  795. // undefined behavior to have a negative bound.
  796. entry = Builder.CreateIntCast(EmitScalarExpr(size), SizeTy,
  797. /*signed*/ false);
  798. }
  799. }
  800. type = vat->getElementType();
  801. break;
  802. }
  803. case Type::FunctionProto:
  804. case Type::FunctionNoProto:
  805. type = cast<FunctionType>(ty)->getResultType();
  806. break;
  807. }
  808. } while (type->isVariablyModifiedType());
  809. }
  810. llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
  811. if (getContext().getBuiltinVaListType()->isArrayType())
  812. return EmitScalarExpr(E);
  813. return EmitLValue(E).getAddress();
  814. }
  815. void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
  816. llvm::Constant *Init) {
  817. assert (Init && "Invalid DeclRefExpr initializer!");
  818. if (CGDebugInfo *Dbg = getDebugInfo())
  819. Dbg->EmitGlobalVariable(E->getDecl(), Init);
  820. }
  821. CodeGenFunction::PeepholeProtection
  822. CodeGenFunction::protectFromPeepholes(RValue rvalue) {
  823. // At the moment, the only aggressive peephole we do in IR gen
  824. // is trunc(zext) folding, but if we add more, we can easily
  825. // extend this protection.
  826. if (!rvalue.isScalar()) return PeepholeProtection();
  827. llvm::Value *value = rvalue.getScalarVal();
  828. if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
  829. // Just make an extra bitcast.
  830. assert(HaveInsertPoint());
  831. llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
  832. Builder.GetInsertBlock());
  833. PeepholeProtection protection;
  834. protection.Inst = inst;
  835. return protection;
  836. }
  837. void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
  838. if (!protection.Inst) return;
  839. // In theory, we could try to duplicate the peepholes now, but whatever.
  840. protection.Inst->eraseFromParent();
  841. }
  842. llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
  843. llvm::Value *AnnotatedVal,
  844. llvm::StringRef AnnotationStr,
  845. SourceLocation Location) {
  846. llvm::Value *Args[4] = {
  847. AnnotatedVal,
  848. Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
  849. Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
  850. CGM.EmitAnnotationLineNo(Location)
  851. };
  852. return Builder.CreateCall(AnnotationFn, Args);
  853. }
  854. void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
  855. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  856. // FIXME We create a new bitcast for every annotation because that's what
  857. // llvm-gcc was doing.
  858. for (specific_attr_iterator<AnnotateAttr>
  859. ai = D->specific_attr_begin<AnnotateAttr>(),
  860. ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
  861. EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
  862. Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
  863. (*ai)->getAnnotation(), D->getLocation());
  864. }
  865. llvm::Value *CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
  866. llvm::Value *V) {
  867. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  868. llvm::Type *VTy = V->getType();
  869. llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
  870. CGM.Int8PtrTy);
  871. for (specific_attr_iterator<AnnotateAttr>
  872. ai = D->specific_attr_begin<AnnotateAttr>(),
  873. ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai) {
  874. // FIXME Always emit the cast inst so we can differentiate between
  875. // annotation on the first field of a struct and annotation on the struct
  876. // itself.
  877. if (VTy != CGM.Int8PtrTy)
  878. V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
  879. V = EmitAnnotationCall(F, V, (*ai)->getAnnotation(), D->getLocation());
  880. V = Builder.CreateBitCast(V, VTy);
  881. }
  882. return V;
  883. }