CodeGenFunction.cpp 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772
  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 "CGCleanup.h"
  15. #include "CGCUDARuntime.h"
  16. #include "CGCXXABI.h"
  17. #include "CGDebugInfo.h"
  18. #include "CGOpenMPRuntime.h"
  19. #include "CodeGenModule.h"
  20. #include "CodeGenPGO.h"
  21. #include "TargetInfo.h"
  22. #include "clang/AST/ASTContext.h"
  23. #include "clang/AST/Decl.h"
  24. #include "clang/AST/DeclCXX.h"
  25. #include "clang/AST/StmtCXX.h"
  26. #include "clang/Basic/TargetInfo.h"
  27. #include "clang/CodeGen/CGFunctionInfo.h"
  28. #include "clang/Frontend/CodeGenOptions.h"
  29. #include "llvm/IR/DataLayout.h"
  30. #include "llvm/IR/Intrinsics.h"
  31. #include "llvm/IR/MDBuilder.h"
  32. #include "llvm/IR/Operator.h"
  33. using namespace clang;
  34. using namespace CodeGen;
  35. CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
  36. : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
  37. Builder(cgm.getModule().getContext(), llvm::ConstantFolder(),
  38. CGBuilderInserterTy(this)),
  39. CurFn(nullptr), CapturedStmtInfo(nullptr),
  40. SanOpts(CGM.getLangOpts().Sanitize), IsSanitizerScope(false),
  41. CurFuncIsThunk(false), AutoreleaseResult(false), SawAsmBlock(false),
  42. IsOutlinedSEHHelper(false), BlockInfo(nullptr), BlockPointer(nullptr),
  43. LambdaThisCaptureField(nullptr), NormalCleanupDest(nullptr),
  44. NextCleanupDestIndex(1), FirstBlockInfo(nullptr), EHResumeBlock(nullptr),
  45. ExceptionSlot(nullptr), EHSelectorSlot(nullptr),
  46. AbnormalTerminationSlot(nullptr), SEHPointersDecl(nullptr),
  47. DebugInfo(CGM.getModuleDebugInfo()), DisableDebugInfo(false),
  48. DidCallStackSave(false), IndirectBranch(nullptr), PGO(cgm),
  49. SwitchInsn(nullptr), SwitchWeights(nullptr), CaseRangeBlock(nullptr),
  50. UnreachableBlock(nullptr), NumReturnExprs(0), NumSimpleReturnExprs(0),
  51. CXXABIThisDecl(nullptr), CXXABIThisValue(nullptr), CXXThisValue(nullptr),
  52. CXXDefaultInitExprThis(nullptr), CXXStructorImplicitParamDecl(nullptr),
  53. CXXStructorImplicitParamValue(nullptr), OutermostConditional(nullptr),
  54. CurLexicalScope(nullptr), TerminateLandingPad(nullptr),
  55. TerminateHandler(nullptr), TrapBB(nullptr) {
  56. if (!suppressNewContext)
  57. CGM.getCXXABI().getMangleContext().startNewFunction();
  58. llvm::FastMathFlags FMF;
  59. if (CGM.getLangOpts().FastMath)
  60. FMF.setUnsafeAlgebra();
  61. if (CGM.getLangOpts().FiniteMathOnly) {
  62. FMF.setNoNaNs();
  63. FMF.setNoInfs();
  64. }
  65. if (CGM.getCodeGenOpts().NoNaNsFPMath) {
  66. FMF.setNoNaNs();
  67. }
  68. if (CGM.getCodeGenOpts().NoSignedZeros) {
  69. FMF.setNoSignedZeros();
  70. }
  71. if (CGM.getCodeGenOpts().ReciprocalMath) {
  72. FMF.setAllowReciprocal();
  73. }
  74. Builder.SetFastMathFlags(FMF);
  75. }
  76. CodeGenFunction::~CodeGenFunction() {
  77. assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
  78. // If there are any unclaimed block infos, go ahead and destroy them
  79. // now. This can happen if IR-gen gets clever and skips evaluating
  80. // something.
  81. if (FirstBlockInfo)
  82. destroyBlockInfos(FirstBlockInfo);
  83. if (getLangOpts().OpenMP) {
  84. CGM.getOpenMPRuntime().functionFinished(*this);
  85. }
  86. }
  87. LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
  88. CharUnits Alignment;
  89. if (CGM.getCXXABI().isTypeInfoCalculable(T)) {
  90. Alignment = getContext().getTypeAlignInChars(T);
  91. unsigned MaxAlign = getContext().getLangOpts().MaxTypeAlign;
  92. if (MaxAlign && Alignment.getQuantity() > MaxAlign &&
  93. !getContext().isAlignmentRequired(T))
  94. Alignment = CharUnits::fromQuantity(MaxAlign);
  95. }
  96. return LValue::MakeAddr(V, T, Alignment, getContext(), CGM.getTBAAInfo(T));
  97. }
  98. llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
  99. return CGM.getTypes().ConvertTypeForMem(T);
  100. }
  101. llvm::Type *CodeGenFunction::ConvertType(QualType T) {
  102. return CGM.getTypes().ConvertType(T);
  103. }
  104. TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
  105. type = type.getCanonicalType();
  106. while (true) {
  107. switch (type->getTypeClass()) {
  108. #define TYPE(name, parent)
  109. #define ABSTRACT_TYPE(name, parent)
  110. #define NON_CANONICAL_TYPE(name, parent) case Type::name:
  111. #define DEPENDENT_TYPE(name, parent) case Type::name:
  112. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
  113. #include "clang/AST/TypeNodes.def"
  114. llvm_unreachable("non-canonical or dependent type in IR-generation");
  115. case Type::Auto:
  116. llvm_unreachable("undeduced auto type in IR-generation");
  117. // Various scalar types.
  118. case Type::Builtin:
  119. case Type::Pointer:
  120. case Type::BlockPointer:
  121. case Type::LValueReference:
  122. case Type::RValueReference:
  123. case Type::MemberPointer:
  124. case Type::Vector:
  125. case Type::ExtVector:
  126. case Type::FunctionProto:
  127. case Type::FunctionNoProto:
  128. case Type::Enum:
  129. case Type::ObjCObjectPointer:
  130. return TEK_Scalar;
  131. // Complexes.
  132. case Type::Complex:
  133. return TEK_Complex;
  134. // Arrays, records, and Objective-C objects.
  135. case Type::ConstantArray:
  136. case Type::IncompleteArray:
  137. case Type::VariableArray:
  138. case Type::Record:
  139. case Type::ObjCObject:
  140. case Type::ObjCInterface:
  141. return TEK_Aggregate;
  142. // We operate on atomic values according to their underlying type.
  143. case Type::Atomic:
  144. type = cast<AtomicType>(type)->getValueType();
  145. continue;
  146. }
  147. llvm_unreachable("unknown type kind!");
  148. }
  149. }
  150. llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
  151. // For cleanliness, we try to avoid emitting the return block for
  152. // simple cases.
  153. llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
  154. if (CurBB) {
  155. assert(!CurBB->getTerminator() && "Unexpected terminated block.");
  156. // We have a valid insert point, reuse it if it is empty or there are no
  157. // explicit jumps to the return block.
  158. if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
  159. ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
  160. delete ReturnBlock.getBlock();
  161. } else
  162. EmitBlock(ReturnBlock.getBlock());
  163. return llvm::DebugLoc();
  164. }
  165. // Otherwise, if the return block is the target of a single direct
  166. // branch then we can just put the code in that block instead. This
  167. // cleans up functions which started with a unified return block.
  168. if (ReturnBlock.getBlock()->hasOneUse()) {
  169. llvm::BranchInst *BI =
  170. dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
  171. if (BI && BI->isUnconditional() &&
  172. BI->getSuccessor(0) == ReturnBlock.getBlock()) {
  173. // Record/return the DebugLoc of the simple 'return' expression to be used
  174. // later by the actual 'ret' instruction.
  175. llvm::DebugLoc Loc = BI->getDebugLoc();
  176. Builder.SetInsertPoint(BI->getParent());
  177. BI->eraseFromParent();
  178. delete ReturnBlock.getBlock();
  179. return Loc;
  180. }
  181. }
  182. // FIXME: We are at an unreachable point, there is no reason to emit the block
  183. // unless it has uses. However, we still need a place to put the debug
  184. // region.end for now.
  185. EmitBlock(ReturnBlock.getBlock());
  186. return llvm::DebugLoc();
  187. }
  188. static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
  189. if (!BB) return;
  190. if (!BB->use_empty())
  191. return CGF.CurFn->getBasicBlockList().push_back(BB);
  192. delete BB;
  193. }
  194. void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
  195. assert(BreakContinueStack.empty() &&
  196. "mismatched push/pop in break/continue stack!");
  197. bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
  198. && NumSimpleReturnExprs == NumReturnExprs
  199. && ReturnBlock.getBlock()->use_empty();
  200. // Usually the return expression is evaluated before the cleanup
  201. // code. If the function contains only a simple return statement,
  202. // such as a constant, the location before the cleanup code becomes
  203. // the last useful breakpoint in the function, because the simple
  204. // return expression will be evaluated after the cleanup code. To be
  205. // safe, set the debug location for cleanup code to the location of
  206. // the return statement. Otherwise the cleanup code should be at the
  207. // end of the function's lexical scope.
  208. //
  209. // If there are multiple branches to the return block, the branch
  210. // instructions will get the location of the return statements and
  211. // all will be fine.
  212. if (CGDebugInfo *DI = getDebugInfo()) {
  213. if (OnlySimpleReturnStmts)
  214. DI->EmitLocation(Builder, LastStopPoint);
  215. else
  216. DI->EmitLocation(Builder, EndLoc);
  217. }
  218. // Pop any cleanups that might have been associated with the
  219. // parameters. Do this in whatever block we're currently in; it's
  220. // important to do this before we enter the return block or return
  221. // edges will be *really* confused.
  222. bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
  223. bool HasOnlyLifetimeMarkers =
  224. HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth);
  225. bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
  226. if (HasCleanups) {
  227. // Make sure the line table doesn't jump back into the body for
  228. // the ret after it's been at EndLoc.
  229. if (CGDebugInfo *DI = getDebugInfo())
  230. if (OnlySimpleReturnStmts)
  231. DI->EmitLocation(Builder, EndLoc);
  232. PopCleanupBlocks(PrologueCleanupDepth);
  233. }
  234. // Emit function epilog (to return).
  235. llvm::DebugLoc Loc = EmitReturnBlock();
  236. if (ShouldInstrumentFunction())
  237. EmitFunctionInstrumentation("__cyg_profile_func_exit");
  238. // Emit debug descriptor for function end.
  239. if (CGDebugInfo *DI = getDebugInfo())
  240. DI->EmitFunctionEnd(Builder);
  241. // Reset the debug location to that of the simple 'return' expression, if any
  242. // rather than that of the end of the function's scope '}'.
  243. ApplyDebugLocation AL(*this, Loc);
  244. EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
  245. EmitEndEHSpec(CurCodeDecl);
  246. assert(EHStack.empty() &&
  247. "did not remove all scopes from cleanup stack!");
  248. // If someone did an indirect goto, emit the indirect goto block at the end of
  249. // the function.
  250. if (IndirectBranch) {
  251. EmitBlock(IndirectBranch->getParent());
  252. Builder.ClearInsertionPoint();
  253. }
  254. // If some of our locals escaped, insert a call to llvm.frameescape in the
  255. // entry block.
  256. if (!EscapedLocals.empty()) {
  257. // Invert the map from local to index into a simple vector. There should be
  258. // no holes.
  259. SmallVector<llvm::Value *, 4> EscapeArgs;
  260. EscapeArgs.resize(EscapedLocals.size());
  261. for (auto &Pair : EscapedLocals)
  262. EscapeArgs[Pair.second] = Pair.first;
  263. llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
  264. &CGM.getModule(), llvm::Intrinsic::frameescape);
  265. CGBuilderTy(AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
  266. }
  267. // Remove the AllocaInsertPt instruction, which is just a convenience for us.
  268. llvm::Instruction *Ptr = AllocaInsertPt;
  269. AllocaInsertPt = nullptr;
  270. Ptr->eraseFromParent();
  271. // If someone took the address of a label but never did an indirect goto, we
  272. // made a zero entry PHI node, which is illegal, zap it now.
  273. if (IndirectBranch) {
  274. llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
  275. if (PN->getNumIncomingValues() == 0) {
  276. PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
  277. PN->eraseFromParent();
  278. }
  279. }
  280. EmitIfUsed(*this, EHResumeBlock);
  281. EmitIfUsed(*this, TerminateLandingPad);
  282. EmitIfUsed(*this, TerminateHandler);
  283. EmitIfUsed(*this, UnreachableBlock);
  284. if (CGM.getCodeGenOpts().EmitDeclMetadata)
  285. EmitDeclMetadata();
  286. for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
  287. I = DeferredReplacements.begin(),
  288. E = DeferredReplacements.end();
  289. I != E; ++I) {
  290. I->first->replaceAllUsesWith(I->second);
  291. I->first->eraseFromParent();
  292. }
  293. }
  294. /// ShouldInstrumentFunction - Return true if the current function should be
  295. /// instrumented with __cyg_profile_func_* calls
  296. bool CodeGenFunction::ShouldInstrumentFunction() {
  297. if (!CGM.getCodeGenOpts().InstrumentFunctions)
  298. return false;
  299. if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
  300. return false;
  301. return true;
  302. }
  303. /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
  304. /// instrumentation function with the current function and the call site, if
  305. /// function instrumentation is enabled.
  306. void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
  307. // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
  308. llvm::PointerType *PointerTy = Int8PtrTy;
  309. llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy };
  310. llvm::FunctionType *FunctionTy =
  311. llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false);
  312. llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
  313. llvm::CallInst *CallSite = Builder.CreateCall(
  314. CGM.getIntrinsic(llvm::Intrinsic::returnaddress),
  315. llvm::ConstantInt::get(Int32Ty, 0),
  316. "callsite");
  317. llvm::Value *args[] = {
  318. llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
  319. CallSite
  320. };
  321. EmitNounwindRuntimeCall(F, args);
  322. }
  323. void CodeGenFunction::EmitMCountInstrumentation() {
  324. llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
  325. llvm::Constant *MCountFn =
  326. CGM.CreateRuntimeFunction(FTy, getTarget().getMCountName());
  327. EmitNounwindRuntimeCall(MCountFn);
  328. }
  329. // OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
  330. // information in the program executable. The argument information stored
  331. // includes the argument name, its type, the address and access qualifiers used.
  332. static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn,
  333. CodeGenModule &CGM, llvm::LLVMContext &Context,
  334. SmallVector<llvm::Metadata *, 5> &kernelMDArgs,
  335. CGBuilderTy &Builder, ASTContext &ASTCtx) {
  336. // Create MDNodes that represent the kernel arg metadata.
  337. // Each MDNode is a list in the form of "key", N number of values which is
  338. // the same number of values as their are kernel arguments.
  339. const PrintingPolicy &Policy = ASTCtx.getPrintingPolicy();
  340. // MDNode for the kernel argument address space qualifiers.
  341. SmallVector<llvm::Metadata *, 8> addressQuals;
  342. addressQuals.push_back(llvm::MDString::get(Context, "kernel_arg_addr_space"));
  343. // MDNode for the kernel argument access qualifiers (images only).
  344. SmallVector<llvm::Metadata *, 8> accessQuals;
  345. accessQuals.push_back(llvm::MDString::get(Context, "kernel_arg_access_qual"));
  346. // MDNode for the kernel argument type names.
  347. SmallVector<llvm::Metadata *, 8> argTypeNames;
  348. argTypeNames.push_back(llvm::MDString::get(Context, "kernel_arg_type"));
  349. // MDNode for the kernel argument base type names.
  350. SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
  351. argBaseTypeNames.push_back(
  352. llvm::MDString::get(Context, "kernel_arg_base_type"));
  353. // MDNode for the kernel argument type qualifiers.
  354. SmallVector<llvm::Metadata *, 8> argTypeQuals;
  355. argTypeQuals.push_back(llvm::MDString::get(Context, "kernel_arg_type_qual"));
  356. // MDNode for the kernel argument names.
  357. SmallVector<llvm::Metadata *, 8> argNames;
  358. argNames.push_back(llvm::MDString::get(Context, "kernel_arg_name"));
  359. for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
  360. const ParmVarDecl *parm = FD->getParamDecl(i);
  361. QualType ty = parm->getType();
  362. std::string typeQuals;
  363. if (ty->isPointerType()) {
  364. QualType pointeeTy = ty->getPointeeType();
  365. // Get address qualifier.
  366. addressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(
  367. ASTCtx.getTargetAddressSpace(pointeeTy.getAddressSpace()))));
  368. // Get argument type name.
  369. std::string typeName =
  370. pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
  371. // Turn "unsigned type" to "utype"
  372. std::string::size_type pos = typeName.find("unsigned");
  373. if (pointeeTy.isCanonical() && pos != std::string::npos)
  374. typeName.erase(pos+1, 8);
  375. argTypeNames.push_back(llvm::MDString::get(Context, typeName));
  376. std::string baseTypeName =
  377. pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
  378. Policy) +
  379. "*";
  380. // Turn "unsigned type" to "utype"
  381. pos = baseTypeName.find("unsigned");
  382. if (pos != std::string::npos)
  383. baseTypeName.erase(pos+1, 8);
  384. argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
  385. // Get argument type qualifiers:
  386. if (ty.isRestrictQualified())
  387. typeQuals = "restrict";
  388. if (pointeeTy.isConstQualified() ||
  389. (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
  390. typeQuals += typeQuals.empty() ? "const" : " const";
  391. if (pointeeTy.isVolatileQualified())
  392. typeQuals += typeQuals.empty() ? "volatile" : " volatile";
  393. } else {
  394. uint32_t AddrSpc = 0;
  395. if (ty->isImageType())
  396. AddrSpc =
  397. CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
  398. addressQuals.push_back(
  399. llvm::ConstantAsMetadata::get(Builder.getInt32(AddrSpc)));
  400. // Get argument type name.
  401. std::string typeName = ty.getUnqualifiedType().getAsString(Policy);
  402. // Turn "unsigned type" to "utype"
  403. std::string::size_type pos = typeName.find("unsigned");
  404. if (ty.isCanonical() && pos != std::string::npos)
  405. typeName.erase(pos+1, 8);
  406. argTypeNames.push_back(llvm::MDString::get(Context, typeName));
  407. std::string baseTypeName =
  408. ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
  409. // Turn "unsigned type" to "utype"
  410. pos = baseTypeName.find("unsigned");
  411. if (pos != std::string::npos)
  412. baseTypeName.erase(pos+1, 8);
  413. argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
  414. // Get argument type qualifiers:
  415. if (ty.isConstQualified())
  416. typeQuals = "const";
  417. if (ty.isVolatileQualified())
  418. typeQuals += typeQuals.empty() ? "volatile" : " volatile";
  419. }
  420. argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals));
  421. // Get image access qualifier:
  422. if (ty->isImageType()) {
  423. const OpenCLImageAccessAttr *A = parm->getAttr<OpenCLImageAccessAttr>();
  424. if (A && A->isWriteOnly())
  425. accessQuals.push_back(llvm::MDString::get(Context, "write_only"));
  426. else
  427. accessQuals.push_back(llvm::MDString::get(Context, "read_only"));
  428. // FIXME: what about read_write?
  429. } else
  430. accessQuals.push_back(llvm::MDString::get(Context, "none"));
  431. // Get argument name.
  432. argNames.push_back(llvm::MDString::get(Context, parm->getName()));
  433. }
  434. kernelMDArgs.push_back(llvm::MDNode::get(Context, addressQuals));
  435. kernelMDArgs.push_back(llvm::MDNode::get(Context, accessQuals));
  436. kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeNames));
  437. kernelMDArgs.push_back(llvm::MDNode::get(Context, argBaseTypeNames));
  438. kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeQuals));
  439. if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
  440. kernelMDArgs.push_back(llvm::MDNode::get(Context, argNames));
  441. }
  442. void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
  443. llvm::Function *Fn)
  444. {
  445. if (!FD->hasAttr<OpenCLKernelAttr>())
  446. return;
  447. llvm::LLVMContext &Context = getLLVMContext();
  448. SmallVector<llvm::Metadata *, 5> kernelMDArgs;
  449. kernelMDArgs.push_back(llvm::ConstantAsMetadata::get(Fn));
  450. GenOpenCLArgMetadata(FD, Fn, CGM, Context, kernelMDArgs, Builder,
  451. getContext());
  452. if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
  453. QualType hintQTy = A->getTypeHint();
  454. const ExtVectorType *hintEltQTy = hintQTy->getAs<ExtVectorType>();
  455. bool isSignedInteger =
  456. hintQTy->isSignedIntegerType() ||
  457. (hintEltQTy && hintEltQTy->getElementType()->isSignedIntegerType());
  458. llvm::Metadata *attrMDArgs[] = {
  459. llvm::MDString::get(Context, "vec_type_hint"),
  460. llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
  461. CGM.getTypes().ConvertType(A->getTypeHint()))),
  462. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  463. llvm::IntegerType::get(Context, 32),
  464. llvm::APInt(32, (uint64_t)(isSignedInteger ? 1 : 0))))};
  465. kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
  466. }
  467. if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
  468. llvm::Metadata *attrMDArgs[] = {
  469. llvm::MDString::get(Context, "work_group_size_hint"),
  470. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
  471. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
  472. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
  473. kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
  474. }
  475. if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
  476. llvm::Metadata *attrMDArgs[] = {
  477. llvm::MDString::get(Context, "reqd_work_group_size"),
  478. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
  479. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
  480. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
  481. kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
  482. }
  483. llvm::MDNode *kernelMDNode = llvm::MDNode::get(Context, kernelMDArgs);
  484. llvm::NamedMDNode *OpenCLKernelMetadata =
  485. CGM.getModule().getOrInsertNamedMetadata("opencl.kernels");
  486. OpenCLKernelMetadata->addOperand(kernelMDNode);
  487. }
  488. /// Determine whether the function F ends with a return stmt.
  489. static bool endsWithReturn(const Decl* F) {
  490. const Stmt *Body = nullptr;
  491. if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
  492. Body = FD->getBody();
  493. else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
  494. Body = OMD->getBody();
  495. if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
  496. auto LastStmt = CS->body_rbegin();
  497. if (LastStmt != CS->body_rend())
  498. return isa<ReturnStmt>(*LastStmt);
  499. }
  500. return false;
  501. }
  502. void CodeGenFunction::StartFunction(GlobalDecl GD,
  503. QualType RetTy,
  504. llvm::Function *Fn,
  505. const CGFunctionInfo &FnInfo,
  506. const FunctionArgList &Args,
  507. SourceLocation Loc,
  508. SourceLocation StartLoc) {
  509. assert(!CurFn &&
  510. "Do not use a CodeGenFunction object for more than one function");
  511. const Decl *D = GD.getDecl();
  512. DidCallStackSave = false;
  513. CurCodeDecl = D;
  514. CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
  515. FnRetTy = RetTy;
  516. CurFn = Fn;
  517. CurFnInfo = &FnInfo;
  518. assert(CurFn->isDeclaration() && "Function already has body?");
  519. if (CGM.isInSanitizerBlacklist(Fn, Loc))
  520. SanOpts.clear();
  521. if (D) {
  522. // Apply the no_sanitize* attributes to SanOpts.
  523. for (auto Attr : D->specific_attrs<NoSanitizeAttr>())
  524. SanOpts.Mask &= ~Attr->getMask();
  525. }
  526. // Apply sanitizer attributes to the function.
  527. if (SanOpts.has(SanitizerKind::Address))
  528. Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
  529. if (SanOpts.has(SanitizerKind::Thread))
  530. Fn->addFnAttr(llvm::Attribute::SanitizeThread);
  531. if (SanOpts.has(SanitizerKind::Memory))
  532. Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
  533. // Pass inline keyword to optimizer if it appears explicitly on any
  534. // declaration. Also, in the case of -fno-inline attach NoInline
  535. // attribute to all function that are not marked AlwaysInline.
  536. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
  537. if (!CGM.getCodeGenOpts().NoInline) {
  538. for (auto RI : FD->redecls())
  539. if (RI->isInlineSpecified()) {
  540. Fn->addFnAttr(llvm::Attribute::InlineHint);
  541. break;
  542. }
  543. } else if (!FD->hasAttr<AlwaysInlineAttr>())
  544. Fn->addFnAttr(llvm::Attribute::NoInline);
  545. }
  546. if (getLangOpts().OpenCL) {
  547. // Add metadata for a kernel function.
  548. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  549. EmitOpenCLKernelMetadata(FD, Fn);
  550. }
  551. // If we are checking function types, emit a function type signature as
  552. // prologue data.
  553. if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
  554. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
  555. if (llvm::Constant *PrologueSig =
  556. CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
  557. llvm::Constant *FTRTTIConst =
  558. CGM.GetAddrOfRTTIDescriptor(FD->getType(), /*ForEH=*/true);
  559. llvm::Constant *PrologueStructElems[] = { PrologueSig, FTRTTIConst };
  560. llvm::Constant *PrologueStructConst =
  561. llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
  562. Fn->setPrologueData(PrologueStructConst);
  563. }
  564. }
  565. }
  566. llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
  567. // Create a marker to make it easy to insert allocas into the entryblock
  568. // later. Don't create this with the builder, because we don't want it
  569. // folded.
  570. llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
  571. AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
  572. if (Builder.isNamePreserving())
  573. AllocaInsertPt->setName("allocapt");
  574. ReturnBlock = getJumpDestInCurrentScope("return");
  575. Builder.SetInsertPoint(EntryBB);
  576. // Emit subprogram debug descriptor.
  577. if (CGDebugInfo *DI = getDebugInfo()) {
  578. SmallVector<QualType, 16> ArgTypes;
  579. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
  580. i != e; ++i) {
  581. ArgTypes.push_back((*i)->getType());
  582. }
  583. QualType FnType =
  584. getContext().getFunctionType(RetTy, ArgTypes,
  585. FunctionProtoType::ExtProtoInfo());
  586. DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, Builder);
  587. }
  588. if (ShouldInstrumentFunction())
  589. EmitFunctionInstrumentation("__cyg_profile_func_enter");
  590. if (CGM.getCodeGenOpts().InstrumentForProfiling)
  591. EmitMCountInstrumentation();
  592. if (RetTy->isVoidType()) {
  593. // Void type; nothing to return.
  594. ReturnValue = nullptr;
  595. // Count the implicit return.
  596. if (!endsWithReturn(D))
  597. ++NumReturnExprs;
  598. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
  599. !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
  600. // Indirect aggregate return; emit returned value directly into sret slot.
  601. // This reduces code size, and affects correctness in C++.
  602. auto AI = CurFn->arg_begin();
  603. if (CurFnInfo->getReturnInfo().isSRetAfterThis())
  604. ++AI;
  605. ReturnValue = AI;
  606. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
  607. !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
  608. // Load the sret pointer from the argument struct and return into that.
  609. unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
  610. llvm::Function::arg_iterator EI = CurFn->arg_end();
  611. --EI;
  612. llvm::Value *Addr = Builder.CreateStructGEP(nullptr, EI, Idx);
  613. ReturnValue = Builder.CreateLoad(Addr, "agg.result");
  614. } else {
  615. ReturnValue = CreateIRTemp(RetTy, "retval");
  616. // Tell the epilog emitter to autorelease the result. We do this
  617. // now so that various specialized functions can suppress it
  618. // during their IR-generation.
  619. if (getLangOpts().ObjCAutoRefCount &&
  620. !CurFnInfo->isReturnsRetained() &&
  621. RetTy->isObjCRetainableType())
  622. AutoreleaseResult = true;
  623. }
  624. EmitStartEHSpec(CurCodeDecl);
  625. PrologueCleanupDepth = EHStack.stable_begin();
  626. EmitFunctionProlog(*CurFnInfo, CurFn, Args);
  627. if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
  628. CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
  629. const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
  630. if (MD->getParent()->isLambda() &&
  631. MD->getOverloadedOperator() == OO_Call) {
  632. // We're in a lambda; figure out the captures.
  633. MD->getParent()->getCaptureFields(LambdaCaptureFields,
  634. LambdaThisCaptureField);
  635. if (LambdaThisCaptureField) {
  636. // If this lambda captures this, load it.
  637. LValue ThisLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
  638. CXXThisValue = EmitLoadOfLValue(ThisLValue,
  639. SourceLocation()).getScalarVal();
  640. }
  641. for (auto *FD : MD->getParent()->fields()) {
  642. if (FD->hasCapturedVLAType()) {
  643. auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
  644. SourceLocation()).getScalarVal();
  645. auto VAT = FD->getCapturedVLAType();
  646. VLASizeMap[VAT->getSizeExpr()] = ExprArg;
  647. }
  648. }
  649. } else {
  650. // Not in a lambda; just use 'this' from the method.
  651. // FIXME: Should we generate a new load for each use of 'this'? The
  652. // fast register allocator would be happier...
  653. CXXThisValue = CXXABIThisValue;
  654. }
  655. }
  656. // If any of the arguments have a variably modified type, make sure to
  657. // emit the type size.
  658. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
  659. i != e; ++i) {
  660. const VarDecl *VD = *i;
  661. // Dig out the type as written from ParmVarDecls; it's unclear whether
  662. // the standard (C99 6.9.1p10) requires this, but we're following the
  663. // precedent set by gcc.
  664. QualType Ty;
  665. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
  666. Ty = PVD->getOriginalType();
  667. else
  668. Ty = VD->getType();
  669. if (Ty->isVariablyModifiedType())
  670. EmitVariablyModifiedType(Ty);
  671. }
  672. // Emit a location at the end of the prologue.
  673. if (CGDebugInfo *DI = getDebugInfo())
  674. DI->EmitLocation(Builder, StartLoc);
  675. }
  676. void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args,
  677. const Stmt *Body) {
  678. incrementProfileCounter(Body);
  679. if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
  680. EmitCompoundStmtWithoutScope(*S);
  681. else
  682. EmitStmt(Body);
  683. }
  684. /// When instrumenting to collect profile data, the counts for some blocks
  685. /// such as switch cases need to not include the fall-through counts, so
  686. /// emit a branch around the instrumentation code. When not instrumenting,
  687. /// this just calls EmitBlock().
  688. void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
  689. const Stmt *S) {
  690. llvm::BasicBlock *SkipCountBB = nullptr;
  691. if (HaveInsertPoint() && CGM.getCodeGenOpts().ProfileInstrGenerate) {
  692. // When instrumenting for profiling, the fallthrough to certain
  693. // statements needs to skip over the instrumentation code so that we
  694. // get an accurate count.
  695. SkipCountBB = createBasicBlock("skipcount");
  696. EmitBranch(SkipCountBB);
  697. }
  698. EmitBlock(BB);
  699. uint64_t CurrentCount = getCurrentProfileCount();
  700. incrementProfileCounter(S);
  701. setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
  702. if (SkipCountBB)
  703. EmitBlock(SkipCountBB);
  704. }
  705. /// Tries to mark the given function nounwind based on the
  706. /// non-existence of any throwing calls within it. We believe this is
  707. /// lightweight enough to do at -O0.
  708. static void TryMarkNoThrow(llvm::Function *F) {
  709. // LLVM treats 'nounwind' on a function as part of the type, so we
  710. // can't do this on functions that can be overwritten.
  711. if (F->mayBeOverridden()) return;
  712. for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
  713. for (llvm::BasicBlock::iterator
  714. BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
  715. if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI)) {
  716. if (!Call->doesNotThrow())
  717. return;
  718. } else if (isa<llvm::ResumeInst>(&*BI)) {
  719. return;
  720. }
  721. F->setDoesNotThrow();
  722. }
  723. void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
  724. const CGFunctionInfo &FnInfo) {
  725. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  726. // Check if we should generate debug info for this function.
  727. if (FD->hasAttr<NoDebugAttr>())
  728. DebugInfo = nullptr; // disable debug info indefinitely for this function
  729. FunctionArgList Args;
  730. QualType ResTy = FD->getReturnType();
  731. CurGD = GD;
  732. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  733. if (MD && MD->isInstance()) {
  734. if (CGM.getCXXABI().HasThisReturn(GD))
  735. ResTy = MD->getThisType(getContext());
  736. else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
  737. ResTy = CGM.getContext().VoidPtrTy;
  738. CGM.getCXXABI().buildThisParam(*this, Args);
  739. }
  740. Args.append(FD->param_begin(), FD->param_end());
  741. if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
  742. CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
  743. SourceRange BodyRange;
  744. if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
  745. CurEHLocation = BodyRange.getEnd();
  746. // Use the location of the start of the function to determine where
  747. // the function definition is located. By default use the location
  748. // of the declaration as the location for the subprogram. A function
  749. // may lack a declaration in the source code if it is created by code
  750. // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
  751. SourceLocation Loc = FD->getLocation();
  752. // If this is a function specialization then use the pattern body
  753. // as the location for the function.
  754. if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
  755. if (SpecDecl->hasBody(SpecDecl))
  756. Loc = SpecDecl->getLocation();
  757. // Emit the standard function prologue.
  758. StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
  759. // Generate the body of the function.
  760. PGO.checkGlobalDecl(GD);
  761. PGO.assignRegionCounters(GD.getDecl(), CurFn);
  762. if (isa<CXXDestructorDecl>(FD))
  763. EmitDestructorBody(Args);
  764. else if (isa<CXXConstructorDecl>(FD))
  765. EmitConstructorBody(Args);
  766. else if (getLangOpts().CUDA &&
  767. !getLangOpts().CUDAIsDevice &&
  768. FD->hasAttr<CUDAGlobalAttr>())
  769. CGM.getCUDARuntime().emitDeviceStub(*this, Args);
  770. else if (isa<CXXConversionDecl>(FD) &&
  771. cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) {
  772. // The lambda conversion to block pointer is special; the semantics can't be
  773. // expressed in the AST, so IRGen needs to special-case it.
  774. EmitLambdaToBlockPointerBody(Args);
  775. } else if (isa<CXXMethodDecl>(FD) &&
  776. cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
  777. // The lambda static invoker function is special, because it forwards or
  778. // clones the body of the function call operator (but is actually static).
  779. EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD));
  780. } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
  781. (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
  782. cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
  783. // Implicit copy-assignment gets the same special treatment as implicit
  784. // copy-constructors.
  785. emitImplicitAssignmentOperatorBody(Args);
  786. } else if (Stmt *Body = FD->getBody()) {
  787. EmitFunctionBody(Args, Body);
  788. } else
  789. llvm_unreachable("no definition for emitted function");
  790. // C++11 [stmt.return]p2:
  791. // Flowing off the end of a function [...] results in undefined behavior in
  792. // a value-returning function.
  793. // C11 6.9.1p12:
  794. // If the '}' that terminates a function is reached, and the value of the
  795. // function call is used by the caller, the behavior is undefined.
  796. if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
  797. !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
  798. if (SanOpts.has(SanitizerKind::Return)) {
  799. SanitizerScope SanScope(this);
  800. llvm::Value *IsFalse = Builder.getFalse();
  801. EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
  802. "missing_return", EmitCheckSourceLocation(FD->getLocation()),
  803. None);
  804. } else if (CGM.getCodeGenOpts().OptimizationLevel == 0)
  805. Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::trap), {});
  806. Builder.CreateUnreachable();
  807. Builder.ClearInsertionPoint();
  808. }
  809. // Emit the standard function epilogue.
  810. FinishFunction(BodyRange.getEnd());
  811. // If we haven't marked the function nothrow through other means, do
  812. // a quick pass now to see if we can.
  813. if (!CurFn->doesNotThrow())
  814. TryMarkNoThrow(CurFn);
  815. }
  816. /// ContainsLabel - Return true if the statement contains a label in it. If
  817. /// this statement is not executed normally, it not containing a label means
  818. /// that we can just remove the code.
  819. bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
  820. // Null statement, not a label!
  821. if (!S) return false;
  822. // If this is a label, we have to emit the code, consider something like:
  823. // if (0) { ... foo: bar(); } goto foo;
  824. //
  825. // TODO: If anyone cared, we could track __label__'s, since we know that you
  826. // can't jump to one from outside their declared region.
  827. if (isa<LabelStmt>(S))
  828. return true;
  829. // If this is a case/default statement, and we haven't seen a switch, we have
  830. // to emit the code.
  831. if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
  832. return true;
  833. // If this is a switch statement, we want to ignore cases below it.
  834. if (isa<SwitchStmt>(S))
  835. IgnoreCaseStmts = true;
  836. // Scan subexpressions for verboten labels.
  837. for (Stmt::const_child_range I = S->children(); I; ++I)
  838. if (ContainsLabel(*I, IgnoreCaseStmts))
  839. return true;
  840. return false;
  841. }
  842. /// containsBreak - Return true if the statement contains a break out of it.
  843. /// If the statement (recursively) contains a switch or loop with a break
  844. /// inside of it, this is fine.
  845. bool CodeGenFunction::containsBreak(const Stmt *S) {
  846. // Null statement, not a label!
  847. if (!S) return false;
  848. // If this is a switch or loop that defines its own break scope, then we can
  849. // include it and anything inside of it.
  850. if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
  851. isa<ForStmt>(S))
  852. return false;
  853. if (isa<BreakStmt>(S))
  854. return true;
  855. // Scan subexpressions for verboten breaks.
  856. for (Stmt::const_child_range I = S->children(); I; ++I)
  857. if (containsBreak(*I))
  858. return true;
  859. return false;
  860. }
  861. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  862. /// to a constant, or if it does but contains a label, return false. If it
  863. /// constant folds return true and set the boolean result in Result.
  864. bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
  865. bool &ResultBool) {
  866. llvm::APSInt ResultInt;
  867. if (!ConstantFoldsToSimpleInteger(Cond, ResultInt))
  868. return false;
  869. ResultBool = ResultInt.getBoolValue();
  870. return true;
  871. }
  872. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  873. /// to a constant, or if it does but contains a label, return false. If it
  874. /// constant folds return true and set the folded value.
  875. bool CodeGenFunction::
  876. ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &ResultInt) {
  877. // FIXME: Rename and handle conversion of other evaluatable things
  878. // to bool.
  879. llvm::APSInt Int;
  880. if (!Cond->EvaluateAsInt(Int, getContext()))
  881. return false; // Not foldable, not integer or not fully evaluatable.
  882. if (CodeGenFunction::ContainsLabel(Cond))
  883. return false; // Contains a label.
  884. ResultInt = Int;
  885. return true;
  886. }
  887. /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
  888. /// statement) to the specified blocks. Based on the condition, this might try
  889. /// to simplify the codegen of the conditional based on the branch.
  890. ///
  891. void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
  892. llvm::BasicBlock *TrueBlock,
  893. llvm::BasicBlock *FalseBlock,
  894. uint64_t TrueCount) {
  895. Cond = Cond->IgnoreParens();
  896. if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
  897. // Handle X && Y in a condition.
  898. if (CondBOp->getOpcode() == BO_LAnd) {
  899. // If we have "1 && X", simplify the code. "0 && X" would have constant
  900. // folded if the case was simple enough.
  901. bool ConstantBool = false;
  902. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  903. ConstantBool) {
  904. // br(1 && X) -> br(X).
  905. incrementProfileCounter(CondBOp);
  906. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
  907. TrueCount);
  908. }
  909. // If we have "X && 1", simplify the code to use an uncond branch.
  910. // "X && 0" would have been constant folded to 0.
  911. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  912. ConstantBool) {
  913. // br(X && 1) -> br(X).
  914. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
  915. TrueCount);
  916. }
  917. // Emit the LHS as a conditional. If the LHS conditional is false, we
  918. // want to jump to the FalseBlock.
  919. llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
  920. // The counter tells us how often we evaluate RHS, and all of TrueCount
  921. // can be propagated to that branch.
  922. uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
  923. ConditionalEvaluation eval(*this);
  924. {
  925. ApplyDebugLocation DL(*this, Cond);
  926. EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
  927. EmitBlock(LHSTrue);
  928. }
  929. incrementProfileCounter(CondBOp);
  930. setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
  931. // Any temporaries created here are conditional.
  932. eval.begin(*this);
  933. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount);
  934. eval.end(*this);
  935. return;
  936. }
  937. if (CondBOp->getOpcode() == BO_LOr) {
  938. // If we have "0 || X", simplify the code. "1 || X" would have constant
  939. // folded if the case was simple enough.
  940. bool ConstantBool = false;
  941. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  942. !ConstantBool) {
  943. // br(0 || X) -> br(X).
  944. incrementProfileCounter(CondBOp);
  945. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
  946. TrueCount);
  947. }
  948. // If we have "X || 0", simplify the code to use an uncond branch.
  949. // "X || 1" would have been constant folded to 1.
  950. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  951. !ConstantBool) {
  952. // br(X || 0) -> br(X).
  953. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
  954. TrueCount);
  955. }
  956. // Emit the LHS as a conditional. If the LHS conditional is true, we
  957. // want to jump to the TrueBlock.
  958. llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
  959. // We have the count for entry to the RHS and for the whole expression
  960. // being true, so we can divy up True count between the short circuit and
  961. // the RHS.
  962. uint64_t LHSCount =
  963. getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
  964. uint64_t RHSCount = TrueCount - LHSCount;
  965. ConditionalEvaluation eval(*this);
  966. {
  967. ApplyDebugLocation DL(*this, Cond);
  968. EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
  969. EmitBlock(LHSFalse);
  970. }
  971. incrementProfileCounter(CondBOp);
  972. setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
  973. // Any temporaries created here are conditional.
  974. eval.begin(*this);
  975. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount);
  976. eval.end(*this);
  977. return;
  978. }
  979. }
  980. if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
  981. // br(!x, t, f) -> br(x, f, t)
  982. if (CondUOp->getOpcode() == UO_LNot) {
  983. // Negate the count.
  984. uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
  985. // Negate the condition and swap the destination blocks.
  986. return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
  987. FalseCount);
  988. }
  989. }
  990. if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
  991. // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
  992. llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
  993. llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
  994. ConditionalEvaluation cond(*this);
  995. EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
  996. getProfileCount(CondOp));
  997. // When computing PGO branch weights, we only know the overall count for
  998. // the true block. This code is essentially doing tail duplication of the
  999. // naive code-gen, introducing new edges for which counts are not
  1000. // available. Divide the counts proportionally between the LHS and RHS of
  1001. // the conditional operator.
  1002. uint64_t LHSScaledTrueCount = 0;
  1003. if (TrueCount) {
  1004. double LHSRatio =
  1005. getProfileCount(CondOp) / (double)getCurrentProfileCount();
  1006. LHSScaledTrueCount = TrueCount * LHSRatio;
  1007. }
  1008. cond.begin(*this);
  1009. EmitBlock(LHSBlock);
  1010. incrementProfileCounter(CondOp);
  1011. {
  1012. ApplyDebugLocation DL(*this, Cond);
  1013. EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
  1014. LHSScaledTrueCount);
  1015. }
  1016. cond.end(*this);
  1017. cond.begin(*this);
  1018. EmitBlock(RHSBlock);
  1019. EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
  1020. TrueCount - LHSScaledTrueCount);
  1021. cond.end(*this);
  1022. return;
  1023. }
  1024. if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
  1025. // Conditional operator handling can give us a throw expression as a
  1026. // condition for a case like:
  1027. // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
  1028. // Fold this to:
  1029. // br(c, throw x, br(y, t, f))
  1030. EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
  1031. return;
  1032. }
  1033. // Create branch weights based on the number of times we get here and the
  1034. // number of times the condition should be true.
  1035. uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
  1036. llvm::MDNode *Weights =
  1037. createProfileWeights(TrueCount, CurrentCount - TrueCount);
  1038. // Emit the code with the fully general case.
  1039. llvm::Value *CondV;
  1040. {
  1041. ApplyDebugLocation DL(*this, Cond);
  1042. CondV = EvaluateExprAsBool(Cond);
  1043. }
  1044. Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights);
  1045. }
  1046. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  1047. /// specified stmt yet.
  1048. void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
  1049. CGM.ErrorUnsupported(S, Type);
  1050. }
  1051. /// emitNonZeroVLAInit - Emit the "zero" initialization of a
  1052. /// variable-length array whose elements have a non-zero bit-pattern.
  1053. ///
  1054. /// \param baseType the inner-most element type of the array
  1055. /// \param src - a char* pointing to the bit-pattern for a single
  1056. /// base element of the array
  1057. /// \param sizeInChars - the total size of the VLA, in chars
  1058. static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
  1059. llvm::Value *dest, llvm::Value *src,
  1060. llvm::Value *sizeInChars) {
  1061. std::pair<CharUnits,CharUnits> baseSizeAndAlign
  1062. = CGF.getContext().getTypeInfoInChars(baseType);
  1063. CGBuilderTy &Builder = CGF.Builder;
  1064. llvm::Value *baseSizeInChars
  1065. = llvm::ConstantInt::get(CGF.IntPtrTy, baseSizeAndAlign.first.getQuantity());
  1066. llvm::Type *i8p = Builder.getInt8PtrTy();
  1067. llvm::Value *begin = Builder.CreateBitCast(dest, i8p, "vla.begin");
  1068. llvm::Value *end = Builder.CreateInBoundsGEP(dest, sizeInChars, "vla.end");
  1069. llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
  1070. llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
  1071. llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
  1072. // Make a loop over the VLA. C99 guarantees that the VLA element
  1073. // count must be nonzero.
  1074. CGF.EmitBlock(loopBB);
  1075. llvm::PHINode *cur = Builder.CreatePHI(i8p, 2, "vla.cur");
  1076. cur->addIncoming(begin, originBB);
  1077. // memcpy the individual element bit-pattern.
  1078. Builder.CreateMemCpy(cur, src, baseSizeInChars,
  1079. baseSizeAndAlign.second.getQuantity(),
  1080. /*volatile*/ false);
  1081. // Go to the next element.
  1082. llvm::Value *next = Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(),
  1083. cur, 1, "vla.next");
  1084. // Leave if that's the end of the VLA.
  1085. llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
  1086. Builder.CreateCondBr(done, contBB, loopBB);
  1087. cur->addIncoming(next, loopBB);
  1088. CGF.EmitBlock(contBB);
  1089. }
  1090. void
  1091. CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
  1092. // Ignore empty classes in C++.
  1093. if (getLangOpts().CPlusPlus) {
  1094. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  1095. if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
  1096. return;
  1097. }
  1098. }
  1099. // Cast the dest ptr to the appropriate i8 pointer type.
  1100. unsigned DestAS =
  1101. cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace();
  1102. llvm::Type *BP = Builder.getInt8PtrTy(DestAS);
  1103. if (DestPtr->getType() != BP)
  1104. DestPtr = Builder.CreateBitCast(DestPtr, BP);
  1105. // Get size and alignment info for this aggregate.
  1106. std::pair<CharUnits, CharUnits> TypeInfo =
  1107. getContext().getTypeInfoInChars(Ty);
  1108. CharUnits Size = TypeInfo.first;
  1109. CharUnits Align = TypeInfo.second;
  1110. llvm::Value *SizeVal;
  1111. const VariableArrayType *vla;
  1112. // Don't bother emitting a zero-byte memset.
  1113. if (Size.isZero()) {
  1114. // But note that getTypeInfo returns 0 for a VLA.
  1115. if (const VariableArrayType *vlaType =
  1116. dyn_cast_or_null<VariableArrayType>(
  1117. getContext().getAsArrayType(Ty))) {
  1118. QualType eltType;
  1119. llvm::Value *numElts;
  1120. std::tie(numElts, eltType) = getVLASize(vlaType);
  1121. SizeVal = numElts;
  1122. CharUnits eltSize = getContext().getTypeSizeInChars(eltType);
  1123. if (!eltSize.isOne())
  1124. SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
  1125. vla = vlaType;
  1126. } else {
  1127. return;
  1128. }
  1129. } else {
  1130. SizeVal = CGM.getSize(Size);
  1131. vla = nullptr;
  1132. }
  1133. // If the type contains a pointer to data member we can't memset it to zero.
  1134. // Instead, create a null constant and copy it to the destination.
  1135. // TODO: there are other patterns besides zero that we can usefully memset,
  1136. // like -1, which happens to be the pattern used by member-pointers.
  1137. if (!CGM.getTypes().isZeroInitializable(Ty)) {
  1138. // For a VLA, emit a single element, then splat that over the VLA.
  1139. if (vla) Ty = getContext().getBaseElementType(vla);
  1140. llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
  1141. llvm::GlobalVariable *NullVariable =
  1142. new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
  1143. /*isConstant=*/true,
  1144. llvm::GlobalVariable::PrivateLinkage,
  1145. NullConstant, Twine());
  1146. llvm::Value *SrcPtr =
  1147. Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy());
  1148. if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
  1149. // Get and call the appropriate llvm.memcpy overload.
  1150. Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity(), false);
  1151. return;
  1152. }
  1153. // Otherwise, just memset the whole thing to zero. This is legal
  1154. // because in LLVM, all default initializers (other than the ones we just
  1155. // handled above) are guaranteed to have a bit pattern of all zeros.
  1156. Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal,
  1157. Align.getQuantity(), false);
  1158. }
  1159. llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
  1160. // Make sure that there is a block for the indirect goto.
  1161. if (!IndirectBranch)
  1162. GetIndirectGotoBlock();
  1163. llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
  1164. // Make sure the indirect branch includes all of the address-taken blocks.
  1165. IndirectBranch->addDestination(BB);
  1166. return llvm::BlockAddress::get(CurFn, BB);
  1167. }
  1168. llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
  1169. // If we already made the indirect branch for indirect goto, return its block.
  1170. if (IndirectBranch) return IndirectBranch->getParent();
  1171. CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
  1172. // Create the PHI node that indirect gotos will add entries to.
  1173. llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
  1174. "indirect.goto.dest");
  1175. // Create the indirect branch instruction.
  1176. IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
  1177. return IndirectBranch->getParent();
  1178. }
  1179. /// Computes the length of an array in elements, as well as the base
  1180. /// element type and a properly-typed first element pointer.
  1181. llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
  1182. QualType &baseType,
  1183. llvm::Value *&addr) {
  1184. const ArrayType *arrayType = origArrayType;
  1185. // If it's a VLA, we have to load the stored size. Note that
  1186. // this is the size of the VLA in bytes, not its size in elements.
  1187. llvm::Value *numVLAElements = nullptr;
  1188. if (isa<VariableArrayType>(arrayType)) {
  1189. numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first;
  1190. // Walk into all VLAs. This doesn't require changes to addr,
  1191. // which has type T* where T is the first non-VLA element type.
  1192. do {
  1193. QualType elementType = arrayType->getElementType();
  1194. arrayType = getContext().getAsArrayType(elementType);
  1195. // If we only have VLA components, 'addr' requires no adjustment.
  1196. if (!arrayType) {
  1197. baseType = elementType;
  1198. return numVLAElements;
  1199. }
  1200. } while (isa<VariableArrayType>(arrayType));
  1201. // We get out here only if we find a constant array type
  1202. // inside the VLA.
  1203. }
  1204. // We have some number of constant-length arrays, so addr should
  1205. // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
  1206. // down to the first element of addr.
  1207. SmallVector<llvm::Value*, 8> gepIndices;
  1208. // GEP down to the array type.
  1209. llvm::ConstantInt *zero = Builder.getInt32(0);
  1210. gepIndices.push_back(zero);
  1211. uint64_t countFromCLAs = 1;
  1212. QualType eltType;
  1213. llvm::ArrayType *llvmArrayType =
  1214. dyn_cast<llvm::ArrayType>(
  1215. cast<llvm::PointerType>(addr->getType())->getElementType());
  1216. while (llvmArrayType) {
  1217. assert(isa<ConstantArrayType>(arrayType));
  1218. assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
  1219. == llvmArrayType->getNumElements());
  1220. gepIndices.push_back(zero);
  1221. countFromCLAs *= llvmArrayType->getNumElements();
  1222. eltType = arrayType->getElementType();
  1223. llvmArrayType =
  1224. dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
  1225. arrayType = getContext().getAsArrayType(arrayType->getElementType());
  1226. assert((!llvmArrayType || arrayType) &&
  1227. "LLVM and Clang types are out-of-synch");
  1228. }
  1229. if (arrayType) {
  1230. // From this point onwards, the Clang array type has been emitted
  1231. // as some other type (probably a packed struct). Compute the array
  1232. // size, and just emit the 'begin' expression as a bitcast.
  1233. while (arrayType) {
  1234. countFromCLAs *=
  1235. cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
  1236. eltType = arrayType->getElementType();
  1237. arrayType = getContext().getAsArrayType(eltType);
  1238. }
  1239. unsigned AddressSpace = addr->getType()->getPointerAddressSpace();
  1240. llvm::Type *BaseType = ConvertType(eltType)->getPointerTo(AddressSpace);
  1241. addr = Builder.CreateBitCast(addr, BaseType, "array.begin");
  1242. } else {
  1243. // Create the actual GEP.
  1244. addr = Builder.CreateInBoundsGEP(addr, gepIndices, "array.begin");
  1245. }
  1246. baseType = eltType;
  1247. llvm::Value *numElements
  1248. = llvm::ConstantInt::get(SizeTy, countFromCLAs);
  1249. // If we had any VLA dimensions, factor them in.
  1250. if (numVLAElements)
  1251. numElements = Builder.CreateNUWMul(numVLAElements, numElements);
  1252. return numElements;
  1253. }
  1254. std::pair<llvm::Value*, QualType>
  1255. CodeGenFunction::getVLASize(QualType type) {
  1256. const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
  1257. assert(vla && "type was not a variable array type!");
  1258. return getVLASize(vla);
  1259. }
  1260. std::pair<llvm::Value*, QualType>
  1261. CodeGenFunction::getVLASize(const VariableArrayType *type) {
  1262. // The number of elements so far; always size_t.
  1263. llvm::Value *numElements = nullptr;
  1264. QualType elementType;
  1265. do {
  1266. elementType = type->getElementType();
  1267. llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
  1268. assert(vlaSize && "no size for VLA!");
  1269. assert(vlaSize->getType() == SizeTy);
  1270. if (!numElements) {
  1271. numElements = vlaSize;
  1272. } else {
  1273. // It's undefined behavior if this wraps around, so mark it that way.
  1274. // FIXME: Teach -fsanitize=undefined to trap this.
  1275. numElements = Builder.CreateNUWMul(numElements, vlaSize);
  1276. }
  1277. } while ((type = getContext().getAsVariableArrayType(elementType)));
  1278. return std::pair<llvm::Value*,QualType>(numElements, elementType);
  1279. }
  1280. void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
  1281. assert(type->isVariablyModifiedType() &&
  1282. "Must pass variably modified type to EmitVLASizes!");
  1283. EnsureInsertPoint();
  1284. // We're going to walk down into the type and look for VLA
  1285. // expressions.
  1286. do {
  1287. assert(type->isVariablyModifiedType());
  1288. const Type *ty = type.getTypePtr();
  1289. switch (ty->getTypeClass()) {
  1290. #define TYPE(Class, Base)
  1291. #define ABSTRACT_TYPE(Class, Base)
  1292. #define NON_CANONICAL_TYPE(Class, Base)
  1293. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  1294. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  1295. #include "clang/AST/TypeNodes.def"
  1296. llvm_unreachable("unexpected dependent type!");
  1297. // These types are never variably-modified.
  1298. case Type::Builtin:
  1299. case Type::Complex:
  1300. case Type::Vector:
  1301. case Type::ExtVector:
  1302. case Type::Record:
  1303. case Type::Enum:
  1304. case Type::Elaborated:
  1305. case Type::TemplateSpecialization:
  1306. case Type::ObjCObject:
  1307. case Type::ObjCInterface:
  1308. case Type::ObjCObjectPointer:
  1309. llvm_unreachable("type class is never variably-modified!");
  1310. case Type::Adjusted:
  1311. type = cast<AdjustedType>(ty)->getAdjustedType();
  1312. break;
  1313. case Type::Decayed:
  1314. type = cast<DecayedType>(ty)->getPointeeType();
  1315. break;
  1316. case Type::Pointer:
  1317. type = cast<PointerType>(ty)->getPointeeType();
  1318. break;
  1319. case Type::BlockPointer:
  1320. type = cast<BlockPointerType>(ty)->getPointeeType();
  1321. break;
  1322. case Type::LValueReference:
  1323. case Type::RValueReference:
  1324. type = cast<ReferenceType>(ty)->getPointeeType();
  1325. break;
  1326. case Type::MemberPointer:
  1327. type = cast<MemberPointerType>(ty)->getPointeeType();
  1328. break;
  1329. case Type::ConstantArray:
  1330. case Type::IncompleteArray:
  1331. // Losing element qualification here is fine.
  1332. type = cast<ArrayType>(ty)->getElementType();
  1333. break;
  1334. case Type::VariableArray: {
  1335. // Losing element qualification here is fine.
  1336. const VariableArrayType *vat = cast<VariableArrayType>(ty);
  1337. // Unknown size indication requires no size computation.
  1338. // Otherwise, evaluate and record it.
  1339. if (const Expr *size = vat->getSizeExpr()) {
  1340. // It's possible that we might have emitted this already,
  1341. // e.g. with a typedef and a pointer to it.
  1342. llvm::Value *&entry = VLASizeMap[size];
  1343. if (!entry) {
  1344. llvm::Value *Size = EmitScalarExpr(size);
  1345. // C11 6.7.6.2p5:
  1346. // If the size is an expression that is not an integer constant
  1347. // expression [...] each time it is evaluated it shall have a value
  1348. // greater than zero.
  1349. if (SanOpts.has(SanitizerKind::VLABound) &&
  1350. size->getType()->isSignedIntegerType()) {
  1351. SanitizerScope SanScope(this);
  1352. llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
  1353. llvm::Constant *StaticArgs[] = {
  1354. EmitCheckSourceLocation(size->getLocStart()),
  1355. EmitCheckTypeDescriptor(size->getType())
  1356. };
  1357. EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero),
  1358. SanitizerKind::VLABound),
  1359. "vla_bound_not_positive", StaticArgs, Size);
  1360. }
  1361. // Always zexting here would be wrong if it weren't
  1362. // undefined behavior to have a negative bound.
  1363. entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
  1364. }
  1365. }
  1366. type = vat->getElementType();
  1367. break;
  1368. }
  1369. case Type::FunctionProto:
  1370. case Type::FunctionNoProto:
  1371. type = cast<FunctionType>(ty)->getReturnType();
  1372. break;
  1373. case Type::Paren:
  1374. case Type::TypeOf:
  1375. case Type::UnaryTransform:
  1376. case Type::Attributed:
  1377. case Type::SubstTemplateTypeParm:
  1378. case Type::PackExpansion:
  1379. // Keep walking after single level desugaring.
  1380. type = type.getSingleStepDesugaredType(getContext());
  1381. break;
  1382. case Type::Typedef:
  1383. case Type::Decltype:
  1384. case Type::Auto:
  1385. // Stop walking: nothing to do.
  1386. return;
  1387. case Type::TypeOfExpr:
  1388. // Stop walking: emit typeof expression.
  1389. EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
  1390. return;
  1391. case Type::Atomic:
  1392. type = cast<AtomicType>(ty)->getValueType();
  1393. break;
  1394. }
  1395. } while (type->isVariablyModifiedType());
  1396. }
  1397. llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
  1398. if (getContext().getBuiltinVaListType()->isArrayType())
  1399. return EmitScalarExpr(E);
  1400. return EmitLValue(E).getAddress();
  1401. }
  1402. void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
  1403. llvm::Constant *Init) {
  1404. assert (Init && "Invalid DeclRefExpr initializer!");
  1405. if (CGDebugInfo *Dbg = getDebugInfo())
  1406. if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
  1407. Dbg->EmitGlobalVariable(E->getDecl(), Init);
  1408. }
  1409. CodeGenFunction::PeepholeProtection
  1410. CodeGenFunction::protectFromPeepholes(RValue rvalue) {
  1411. // At the moment, the only aggressive peephole we do in IR gen
  1412. // is trunc(zext) folding, but if we add more, we can easily
  1413. // extend this protection.
  1414. if (!rvalue.isScalar()) return PeepholeProtection();
  1415. llvm::Value *value = rvalue.getScalarVal();
  1416. if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
  1417. // Just make an extra bitcast.
  1418. assert(HaveInsertPoint());
  1419. llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
  1420. Builder.GetInsertBlock());
  1421. PeepholeProtection protection;
  1422. protection.Inst = inst;
  1423. return protection;
  1424. }
  1425. void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
  1426. if (!protection.Inst) return;
  1427. // In theory, we could try to duplicate the peepholes now, but whatever.
  1428. protection.Inst->eraseFromParent();
  1429. }
  1430. llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
  1431. llvm::Value *AnnotatedVal,
  1432. StringRef AnnotationStr,
  1433. SourceLocation Location) {
  1434. llvm::Value *Args[4] = {
  1435. AnnotatedVal,
  1436. Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
  1437. Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
  1438. CGM.EmitAnnotationLineNo(Location)
  1439. };
  1440. return Builder.CreateCall(AnnotationFn, Args);
  1441. }
  1442. void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
  1443. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1444. // FIXME We create a new bitcast for every annotation because that's what
  1445. // llvm-gcc was doing.
  1446. for (const auto *I : D->specific_attrs<AnnotateAttr>())
  1447. EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
  1448. Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
  1449. I->getAnnotation(), D->getLocation());
  1450. }
  1451. llvm::Value *CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
  1452. llvm::Value *V) {
  1453. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1454. llvm::Type *VTy = V->getType();
  1455. llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
  1456. CGM.Int8PtrTy);
  1457. for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
  1458. // FIXME Always emit the cast inst so we can differentiate between
  1459. // annotation on the first field of a struct and annotation on the struct
  1460. // itself.
  1461. if (VTy != CGM.Int8PtrTy)
  1462. V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
  1463. V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation());
  1464. V = Builder.CreateBitCast(V, VTy);
  1465. }
  1466. return V;
  1467. }
  1468. CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
  1469. CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
  1470. : CGF(CGF) {
  1471. assert(!CGF->IsSanitizerScope);
  1472. CGF->IsSanitizerScope = true;
  1473. }
  1474. CodeGenFunction::SanitizerScope::~SanitizerScope() {
  1475. CGF->IsSanitizerScope = false;
  1476. }
  1477. void CodeGenFunction::InsertHelper(llvm::Instruction *I,
  1478. const llvm::Twine &Name,
  1479. llvm::BasicBlock *BB,
  1480. llvm::BasicBlock::iterator InsertPt) const {
  1481. LoopStack.InsertHelper(I);
  1482. if (IsSanitizerScope)
  1483. CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
  1484. }
  1485. template <bool PreserveNames>
  1486. void CGBuilderInserter<PreserveNames>::InsertHelper(
  1487. llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
  1488. llvm::BasicBlock::iterator InsertPt) const {
  1489. llvm::IRBuilderDefaultInserter<PreserveNames>::InsertHelper(I, Name, BB,
  1490. InsertPt);
  1491. if (CGF)
  1492. CGF->InsertHelper(I, Name, BB, InsertPt);
  1493. }
  1494. #ifdef NDEBUG
  1495. #define PreserveNames false
  1496. #else
  1497. #define PreserveNames true
  1498. #endif
  1499. template void CGBuilderInserter<PreserveNames>::InsertHelper(
  1500. llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
  1501. llvm::BasicBlock::iterator InsertPt) const;
  1502. #undef PreserveNames