CodeGenFunction.cpp 93 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468
  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 "CGBlocks.h"
  15. #include "CGCleanup.h"
  16. #include "CGCUDARuntime.h"
  17. #include "CGCXXABI.h"
  18. #include "CGDebugInfo.h"
  19. #include "CGOpenMPRuntime.h"
  20. #include "CodeGenModule.h"
  21. #include "CodeGenPGO.h"
  22. #include "TargetInfo.h"
  23. #include "clang/AST/ASTContext.h"
  24. #include "clang/AST/ASTLambda.h"
  25. #include "clang/AST/Decl.h"
  26. #include "clang/AST/DeclCXX.h"
  27. #include "clang/AST/StmtCXX.h"
  28. #include "clang/AST/StmtObjC.h"
  29. #include "clang/Basic/Builtins.h"
  30. #include "clang/Basic/TargetInfo.h"
  31. #include "clang/CodeGen/CGFunctionInfo.h"
  32. #include "clang/Frontend/CodeGenOptions.h"
  33. #include "clang/Sema/SemaDiagnostic.h"
  34. #include "llvm/IR/DataLayout.h"
  35. #include "llvm/IR/Dominators.h"
  36. #include "llvm/IR/Intrinsics.h"
  37. #include "llvm/IR/MDBuilder.h"
  38. #include "llvm/IR/Operator.h"
  39. #include "llvm/Transforms/Utils/PromoteMemToReg.h"
  40. using namespace clang;
  41. using namespace CodeGen;
  42. /// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
  43. /// markers.
  44. static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
  45. const LangOptions &LangOpts) {
  46. if (CGOpts.DisableLifetimeMarkers)
  47. return false;
  48. // Disable lifetime markers in msan builds.
  49. // FIXME: Remove this when msan works with lifetime markers.
  50. if (LangOpts.Sanitize.has(SanitizerKind::Memory))
  51. return false;
  52. // Asan uses markers for use-after-scope checks.
  53. if (CGOpts.SanitizeAddressUseAfterScope)
  54. return true;
  55. // For now, only in optimized builds.
  56. return CGOpts.OptimizationLevel != 0;
  57. }
  58. CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
  59. : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
  60. Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
  61. CGBuilderInserterTy(this)),
  62. SanOpts(CGM.getLangOpts().Sanitize), DebugInfo(CGM.getModuleDebugInfo()),
  63. PGO(cgm), ShouldEmitLifetimeMarkers(shouldEmitLifetimeMarkers(
  64. CGM.getCodeGenOpts(), CGM.getLangOpts())) {
  65. if (!suppressNewContext)
  66. CGM.getCXXABI().getMangleContext().startNewFunction();
  67. llvm::FastMathFlags FMF;
  68. if (CGM.getLangOpts().FastMath)
  69. FMF.setFast();
  70. if (CGM.getLangOpts().FiniteMathOnly) {
  71. FMF.setNoNaNs();
  72. FMF.setNoInfs();
  73. }
  74. if (CGM.getCodeGenOpts().NoNaNsFPMath) {
  75. FMF.setNoNaNs();
  76. }
  77. if (CGM.getCodeGenOpts().NoSignedZeros) {
  78. FMF.setNoSignedZeros();
  79. }
  80. if (CGM.getCodeGenOpts().ReciprocalMath) {
  81. FMF.setAllowReciprocal();
  82. }
  83. if (CGM.getCodeGenOpts().Reassociate) {
  84. FMF.setAllowReassoc();
  85. }
  86. Builder.setFastMathFlags(FMF);
  87. }
  88. CodeGenFunction::~CodeGenFunction() {
  89. assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
  90. // If there are any unclaimed block infos, go ahead and destroy them
  91. // now. This can happen if IR-gen gets clever and skips evaluating
  92. // something.
  93. if (FirstBlockInfo)
  94. destroyBlockInfos(FirstBlockInfo);
  95. if (getLangOpts().OpenMP && CurFn)
  96. CGM.getOpenMPRuntime().functionFinished(*this);
  97. }
  98. CharUnits CodeGenFunction::getNaturalPointeeTypeAlignment(QualType T,
  99. LValueBaseInfo *BaseInfo,
  100. TBAAAccessInfo *TBAAInfo) {
  101. return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
  102. /* forPointeeType= */ true);
  103. }
  104. CharUnits CodeGenFunction::getNaturalTypeAlignment(QualType T,
  105. LValueBaseInfo *BaseInfo,
  106. TBAAAccessInfo *TBAAInfo,
  107. bool forPointeeType) {
  108. if (TBAAInfo)
  109. *TBAAInfo = CGM.getTBAAAccessInfo(T);
  110. // Honor alignment typedef attributes even on incomplete types.
  111. // We also honor them straight for C++ class types, even as pointees;
  112. // there's an expressivity gap here.
  113. if (auto TT = T->getAs<TypedefType>()) {
  114. if (auto Align = TT->getDecl()->getMaxAlignment()) {
  115. if (BaseInfo)
  116. *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
  117. return getContext().toCharUnitsFromBits(Align);
  118. }
  119. }
  120. if (BaseInfo)
  121. *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
  122. CharUnits Alignment;
  123. if (T->isIncompleteType()) {
  124. Alignment = CharUnits::One(); // Shouldn't be used, but pessimistic is best.
  125. } else {
  126. // For C++ class pointees, we don't know whether we're pointing at a
  127. // base or a complete object, so we generally need to use the
  128. // non-virtual alignment.
  129. const CXXRecordDecl *RD;
  130. if (forPointeeType && (RD = T->getAsCXXRecordDecl())) {
  131. Alignment = CGM.getClassPointerAlignment(RD);
  132. } else {
  133. Alignment = getContext().getTypeAlignInChars(T);
  134. if (T.getQualifiers().hasUnaligned())
  135. Alignment = CharUnits::One();
  136. }
  137. // Cap to the global maximum type alignment unless the alignment
  138. // was somehow explicit on the type.
  139. if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
  140. if (Alignment.getQuantity() > MaxAlign &&
  141. !getContext().isAlignmentRequired(T))
  142. Alignment = CharUnits::fromQuantity(MaxAlign);
  143. }
  144. }
  145. return Alignment;
  146. }
  147. LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
  148. LValueBaseInfo BaseInfo;
  149. TBAAAccessInfo TBAAInfo;
  150. CharUnits Alignment = getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo);
  151. return LValue::MakeAddr(Address(V, Alignment), T, getContext(), BaseInfo,
  152. TBAAInfo);
  153. }
  154. /// Given a value of type T* that may not be to a complete object,
  155. /// construct an l-value with the natural pointee alignment of T.
  156. LValue
  157. CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
  158. LValueBaseInfo BaseInfo;
  159. TBAAAccessInfo TBAAInfo;
  160. CharUnits Align = getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo,
  161. /* forPointeeType= */ true);
  162. return MakeAddrLValue(Address(V, Align), T, BaseInfo, TBAAInfo);
  163. }
  164. llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
  165. return CGM.getTypes().ConvertTypeForMem(T);
  166. }
  167. llvm::Type *CodeGenFunction::ConvertType(QualType T) {
  168. return CGM.getTypes().ConvertType(T);
  169. }
  170. TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
  171. type = type.getCanonicalType();
  172. while (true) {
  173. switch (type->getTypeClass()) {
  174. #define TYPE(name, parent)
  175. #define ABSTRACT_TYPE(name, parent)
  176. #define NON_CANONICAL_TYPE(name, parent) case Type::name:
  177. #define DEPENDENT_TYPE(name, parent) case Type::name:
  178. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
  179. #include "clang/AST/TypeNodes.def"
  180. llvm_unreachable("non-canonical or dependent type in IR-generation");
  181. case Type::Auto:
  182. case Type::DeducedTemplateSpecialization:
  183. llvm_unreachable("undeduced type in IR-generation");
  184. // Various scalar types.
  185. case Type::Builtin:
  186. case Type::Pointer:
  187. case Type::BlockPointer:
  188. case Type::LValueReference:
  189. case Type::RValueReference:
  190. case Type::MemberPointer:
  191. case Type::Vector:
  192. case Type::ExtVector:
  193. case Type::FunctionProto:
  194. case Type::FunctionNoProto:
  195. case Type::Enum:
  196. case Type::ObjCObjectPointer:
  197. case Type::Pipe:
  198. return TEK_Scalar;
  199. // Complexes.
  200. case Type::Complex:
  201. return TEK_Complex;
  202. // Arrays, records, and Objective-C objects.
  203. case Type::ConstantArray:
  204. case Type::IncompleteArray:
  205. case Type::VariableArray:
  206. case Type::Record:
  207. case Type::ObjCObject:
  208. case Type::ObjCInterface:
  209. return TEK_Aggregate;
  210. // We operate on atomic values according to their underlying type.
  211. case Type::Atomic:
  212. type = cast<AtomicType>(type)->getValueType();
  213. continue;
  214. }
  215. llvm_unreachable("unknown type kind!");
  216. }
  217. }
  218. llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
  219. // For cleanliness, we try to avoid emitting the return block for
  220. // simple cases.
  221. llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
  222. if (CurBB) {
  223. assert(!CurBB->getTerminator() && "Unexpected terminated block.");
  224. // We have a valid insert point, reuse it if it is empty or there are no
  225. // explicit jumps to the return block.
  226. if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
  227. ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
  228. delete ReturnBlock.getBlock();
  229. } else
  230. EmitBlock(ReturnBlock.getBlock());
  231. return llvm::DebugLoc();
  232. }
  233. // Otherwise, if the return block is the target of a single direct
  234. // branch then we can just put the code in that block instead. This
  235. // cleans up functions which started with a unified return block.
  236. if (ReturnBlock.getBlock()->hasOneUse()) {
  237. llvm::BranchInst *BI =
  238. dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
  239. if (BI && BI->isUnconditional() &&
  240. BI->getSuccessor(0) == ReturnBlock.getBlock()) {
  241. // Record/return the DebugLoc of the simple 'return' expression to be used
  242. // later by the actual 'ret' instruction.
  243. llvm::DebugLoc Loc = BI->getDebugLoc();
  244. Builder.SetInsertPoint(BI->getParent());
  245. BI->eraseFromParent();
  246. delete ReturnBlock.getBlock();
  247. return Loc;
  248. }
  249. }
  250. // FIXME: We are at an unreachable point, there is no reason to emit the block
  251. // unless it has uses. However, we still need a place to put the debug
  252. // region.end for now.
  253. EmitBlock(ReturnBlock.getBlock());
  254. return llvm::DebugLoc();
  255. }
  256. static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
  257. if (!BB) return;
  258. if (!BB->use_empty())
  259. return CGF.CurFn->getBasicBlockList().push_back(BB);
  260. delete BB;
  261. }
  262. void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
  263. assert(BreakContinueStack.empty() &&
  264. "mismatched push/pop in break/continue stack!");
  265. bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
  266. && NumSimpleReturnExprs == NumReturnExprs
  267. && ReturnBlock.getBlock()->use_empty();
  268. // Usually the return expression is evaluated before the cleanup
  269. // code. If the function contains only a simple return statement,
  270. // such as a constant, the location before the cleanup code becomes
  271. // the last useful breakpoint in the function, because the simple
  272. // return expression will be evaluated after the cleanup code. To be
  273. // safe, set the debug location for cleanup code to the location of
  274. // the return statement. Otherwise the cleanup code should be at the
  275. // end of the function's lexical scope.
  276. //
  277. // If there are multiple branches to the return block, the branch
  278. // instructions will get the location of the return statements and
  279. // all will be fine.
  280. if (CGDebugInfo *DI = getDebugInfo()) {
  281. if (OnlySimpleReturnStmts)
  282. DI->EmitLocation(Builder, LastStopPoint);
  283. else
  284. DI->EmitLocation(Builder, EndLoc);
  285. }
  286. // Pop any cleanups that might have been associated with the
  287. // parameters. Do this in whatever block we're currently in; it's
  288. // important to do this before we enter the return block or return
  289. // edges will be *really* confused.
  290. bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
  291. bool HasOnlyLifetimeMarkers =
  292. HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth);
  293. bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
  294. if (HasCleanups) {
  295. // Make sure the line table doesn't jump back into the body for
  296. // the ret after it's been at EndLoc.
  297. if (CGDebugInfo *DI = getDebugInfo())
  298. if (OnlySimpleReturnStmts)
  299. DI->EmitLocation(Builder, EndLoc);
  300. PopCleanupBlocks(PrologueCleanupDepth);
  301. }
  302. // Emit function epilog (to return).
  303. llvm::DebugLoc Loc = EmitReturnBlock();
  304. if (ShouldInstrumentFunction()) {
  305. if (CGM.getCodeGenOpts().InstrumentFunctions)
  306. CurFn->addFnAttr("instrument-function-exit", "__cyg_profile_func_exit");
  307. if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
  308. CurFn->addFnAttr("instrument-function-exit-inlined",
  309. "__cyg_profile_func_exit");
  310. }
  311. // Emit debug descriptor for function end.
  312. if (CGDebugInfo *DI = getDebugInfo())
  313. DI->EmitFunctionEnd(Builder, CurFn);
  314. // Reset the debug location to that of the simple 'return' expression, if any
  315. // rather than that of the end of the function's scope '}'.
  316. ApplyDebugLocation AL(*this, Loc);
  317. EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
  318. EmitEndEHSpec(CurCodeDecl);
  319. assert(EHStack.empty() &&
  320. "did not remove all scopes from cleanup stack!");
  321. // If someone did an indirect goto, emit the indirect goto block at the end of
  322. // the function.
  323. if (IndirectBranch) {
  324. EmitBlock(IndirectBranch->getParent());
  325. Builder.ClearInsertionPoint();
  326. }
  327. // If some of our locals escaped, insert a call to llvm.localescape in the
  328. // entry block.
  329. if (!EscapedLocals.empty()) {
  330. // Invert the map from local to index into a simple vector. There should be
  331. // no holes.
  332. SmallVector<llvm::Value *, 4> EscapeArgs;
  333. EscapeArgs.resize(EscapedLocals.size());
  334. for (auto &Pair : EscapedLocals)
  335. EscapeArgs[Pair.second] = Pair.first;
  336. llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
  337. &CGM.getModule(), llvm::Intrinsic::localescape);
  338. CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
  339. }
  340. // Remove the AllocaInsertPt instruction, which is just a convenience for us.
  341. llvm::Instruction *Ptr = AllocaInsertPt;
  342. AllocaInsertPt = nullptr;
  343. Ptr->eraseFromParent();
  344. // If someone took the address of a label but never did an indirect goto, we
  345. // made a zero entry PHI node, which is illegal, zap it now.
  346. if (IndirectBranch) {
  347. llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
  348. if (PN->getNumIncomingValues() == 0) {
  349. PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
  350. PN->eraseFromParent();
  351. }
  352. }
  353. EmitIfUsed(*this, EHResumeBlock);
  354. EmitIfUsed(*this, TerminateLandingPad);
  355. EmitIfUsed(*this, TerminateHandler);
  356. EmitIfUsed(*this, UnreachableBlock);
  357. for (const auto &FuncletAndParent : TerminateFunclets)
  358. EmitIfUsed(*this, FuncletAndParent.second);
  359. if (CGM.getCodeGenOpts().EmitDeclMetadata)
  360. EmitDeclMetadata();
  361. for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
  362. I = DeferredReplacements.begin(),
  363. E = DeferredReplacements.end();
  364. I != E; ++I) {
  365. I->first->replaceAllUsesWith(I->second);
  366. I->first->eraseFromParent();
  367. }
  368. // Eliminate CleanupDestSlot alloca by replacing it with SSA values and
  369. // PHIs if the current function is a coroutine. We don't do it for all
  370. // functions as it may result in slight increase in numbers of instructions
  371. // if compiled with no optimizations. We do it for coroutine as the lifetime
  372. // of CleanupDestSlot alloca make correct coroutine frame building very
  373. // difficult.
  374. if (NormalCleanupDest.isValid() && isCoroutine()) {
  375. llvm::DominatorTree DT(*CurFn);
  376. llvm::PromoteMemToReg(
  377. cast<llvm::AllocaInst>(NormalCleanupDest.getPointer()), DT);
  378. NormalCleanupDest = Address::invalid();
  379. }
  380. // Scan function arguments for vector width.
  381. for (llvm::Argument &A : CurFn->args())
  382. if (auto *VT = dyn_cast<llvm::VectorType>(A.getType()))
  383. LargestVectorWidth = std::max(LargestVectorWidth,
  384. VT->getPrimitiveSizeInBits());
  385. // Update vector width based on return type.
  386. if (auto *VT = dyn_cast<llvm::VectorType>(CurFn->getReturnType()))
  387. LargestVectorWidth = std::max(LargestVectorWidth,
  388. VT->getPrimitiveSizeInBits());
  389. // Add the required-vector-width attribute. This contains the max width from:
  390. // 1. min-vector-width attribute used in the source program.
  391. // 2. Any builtins used that have a vector width specified.
  392. // 3. Values passed in and out of inline assembly.
  393. // 4. Width of vector arguments and return types for this function.
  394. // 5. Width of vector aguments and return types for functions called by this
  395. // function.
  396. CurFn->addFnAttr("min-legal-vector-width", llvm::utostr(LargestVectorWidth));
  397. }
  398. /// ShouldInstrumentFunction - Return true if the current function should be
  399. /// instrumented with __cyg_profile_func_* calls
  400. bool CodeGenFunction::ShouldInstrumentFunction() {
  401. if (!CGM.getCodeGenOpts().InstrumentFunctions &&
  402. !CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining &&
  403. !CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
  404. return false;
  405. if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
  406. return false;
  407. return true;
  408. }
  409. /// ShouldXRayInstrument - Return true if the current function should be
  410. /// instrumented with XRay nop sleds.
  411. bool CodeGenFunction::ShouldXRayInstrumentFunction() const {
  412. return CGM.getCodeGenOpts().XRayInstrumentFunctions;
  413. }
  414. /// AlwaysEmitXRayCustomEvents - Return true if we should emit IR for calls to
  415. /// the __xray_customevent(...) builtin calls, when doing XRay instrumentation.
  416. bool CodeGenFunction::AlwaysEmitXRayCustomEvents() const {
  417. return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
  418. (CGM.getCodeGenOpts().XRayAlwaysEmitCustomEvents ||
  419. CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
  420. XRayInstrKind::Custom);
  421. }
  422. bool CodeGenFunction::AlwaysEmitXRayTypedEvents() const {
  423. return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
  424. (CGM.getCodeGenOpts().XRayAlwaysEmitTypedEvents ||
  425. CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
  426. XRayInstrKind::Typed);
  427. }
  428. llvm::Constant *
  429. CodeGenFunction::EncodeAddrForUseInPrologue(llvm::Function *F,
  430. llvm::Constant *Addr) {
  431. // Addresses stored in prologue data can't require run-time fixups and must
  432. // be PC-relative. Run-time fixups are undesirable because they necessitate
  433. // writable text segments, which are unsafe. And absolute addresses are
  434. // undesirable because they break PIE mode.
  435. // Add a layer of indirection through a private global. Taking its address
  436. // won't result in a run-time fixup, even if Addr has linkonce_odr linkage.
  437. auto *GV = new llvm::GlobalVariable(CGM.getModule(), Addr->getType(),
  438. /*isConstant=*/true,
  439. llvm::GlobalValue::PrivateLinkage, Addr);
  440. // Create a PC-relative address.
  441. auto *GOTAsInt = llvm::ConstantExpr::getPtrToInt(GV, IntPtrTy);
  442. auto *FuncAsInt = llvm::ConstantExpr::getPtrToInt(F, IntPtrTy);
  443. auto *PCRelAsInt = llvm::ConstantExpr::getSub(GOTAsInt, FuncAsInt);
  444. return (IntPtrTy == Int32Ty)
  445. ? PCRelAsInt
  446. : llvm::ConstantExpr::getTrunc(PCRelAsInt, Int32Ty);
  447. }
  448. llvm::Value *
  449. CodeGenFunction::DecodeAddrUsedInPrologue(llvm::Value *F,
  450. llvm::Value *EncodedAddr) {
  451. // Reconstruct the address of the global.
  452. auto *PCRelAsInt = Builder.CreateSExt(EncodedAddr, IntPtrTy);
  453. auto *FuncAsInt = Builder.CreatePtrToInt(F, IntPtrTy, "func_addr.int");
  454. auto *GOTAsInt = Builder.CreateAdd(PCRelAsInt, FuncAsInt, "global_addr.int");
  455. auto *GOTAddr = Builder.CreateIntToPtr(GOTAsInt, Int8PtrPtrTy, "global_addr");
  456. // Load the original pointer through the global.
  457. return Builder.CreateLoad(Address(GOTAddr, getPointerAlign()),
  458. "decoded_addr");
  459. }
  460. static void removeImageAccessQualifier(std::string& TyName) {
  461. std::string ReadOnlyQual("__read_only");
  462. std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
  463. if (ReadOnlyPos != std::string::npos)
  464. // "+ 1" for the space after access qualifier.
  465. TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
  466. else {
  467. std::string WriteOnlyQual("__write_only");
  468. std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
  469. if (WriteOnlyPos != std::string::npos)
  470. TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
  471. else {
  472. std::string ReadWriteQual("__read_write");
  473. std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
  474. if (ReadWritePos != std::string::npos)
  475. TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
  476. }
  477. }
  478. }
  479. // Returns the address space id that should be produced to the
  480. // kernel_arg_addr_space metadata. This is always fixed to the ids
  481. // as specified in the SPIR 2.0 specification in order to differentiate
  482. // for example in clGetKernelArgInfo() implementation between the address
  483. // spaces with targets without unique mapping to the OpenCL address spaces
  484. // (basically all single AS CPUs).
  485. static unsigned ArgInfoAddressSpace(LangAS AS) {
  486. switch (AS) {
  487. case LangAS::opencl_global: return 1;
  488. case LangAS::opencl_constant: return 2;
  489. case LangAS::opencl_local: return 3;
  490. case LangAS::opencl_generic: return 4; // Not in SPIR 2.0 specs.
  491. default:
  492. return 0; // Assume private.
  493. }
  494. }
  495. // OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
  496. // information in the program executable. The argument information stored
  497. // includes the argument name, its type, the address and access qualifiers used.
  498. static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn,
  499. CodeGenModule &CGM, llvm::LLVMContext &Context,
  500. CGBuilderTy &Builder, ASTContext &ASTCtx) {
  501. // Create MDNodes that represent the kernel arg metadata.
  502. // Each MDNode is a list in the form of "key", N number of values which is
  503. // the same number of values as their are kernel arguments.
  504. const PrintingPolicy &Policy = ASTCtx.getPrintingPolicy();
  505. // MDNode for the kernel argument address space qualifiers.
  506. SmallVector<llvm::Metadata *, 8> addressQuals;
  507. // MDNode for the kernel argument access qualifiers (images only).
  508. SmallVector<llvm::Metadata *, 8> accessQuals;
  509. // MDNode for the kernel argument type names.
  510. SmallVector<llvm::Metadata *, 8> argTypeNames;
  511. // MDNode for the kernel argument base type names.
  512. SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
  513. // MDNode for the kernel argument type qualifiers.
  514. SmallVector<llvm::Metadata *, 8> argTypeQuals;
  515. // MDNode for the kernel argument names.
  516. SmallVector<llvm::Metadata *, 8> argNames;
  517. for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
  518. const ParmVarDecl *parm = FD->getParamDecl(i);
  519. QualType ty = parm->getType();
  520. std::string typeQuals;
  521. if (ty->isPointerType()) {
  522. QualType pointeeTy = ty->getPointeeType();
  523. // Get address qualifier.
  524. addressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(
  525. ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
  526. // Get argument type name.
  527. std::string typeName =
  528. pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
  529. // Turn "unsigned type" to "utype"
  530. std::string::size_type pos = typeName.find("unsigned");
  531. if (pointeeTy.isCanonical() && pos != std::string::npos)
  532. typeName.erase(pos+1, 8);
  533. argTypeNames.push_back(llvm::MDString::get(Context, typeName));
  534. std::string baseTypeName =
  535. pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
  536. Policy) +
  537. "*";
  538. // Turn "unsigned type" to "utype"
  539. pos = baseTypeName.find("unsigned");
  540. if (pos != std::string::npos)
  541. baseTypeName.erase(pos+1, 8);
  542. argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
  543. // Get argument type qualifiers:
  544. if (ty.isRestrictQualified())
  545. typeQuals = "restrict";
  546. if (pointeeTy.isConstQualified() ||
  547. (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
  548. typeQuals += typeQuals.empty() ? "const" : " const";
  549. if (pointeeTy.isVolatileQualified())
  550. typeQuals += typeQuals.empty() ? "volatile" : " volatile";
  551. } else {
  552. uint32_t AddrSpc = 0;
  553. bool isPipe = ty->isPipeType();
  554. if (ty->isImageType() || isPipe)
  555. AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
  556. addressQuals.push_back(
  557. llvm::ConstantAsMetadata::get(Builder.getInt32(AddrSpc)));
  558. // Get argument type name.
  559. std::string typeName;
  560. if (isPipe)
  561. typeName = ty.getCanonicalType()->getAs<PipeType>()->getElementType()
  562. .getAsString(Policy);
  563. else
  564. typeName = ty.getUnqualifiedType().getAsString(Policy);
  565. // Turn "unsigned type" to "utype"
  566. std::string::size_type pos = typeName.find("unsigned");
  567. if (ty.isCanonical() && pos != std::string::npos)
  568. typeName.erase(pos+1, 8);
  569. std::string baseTypeName;
  570. if (isPipe)
  571. baseTypeName = ty.getCanonicalType()->getAs<PipeType>()
  572. ->getElementType().getCanonicalType()
  573. .getAsString(Policy);
  574. else
  575. baseTypeName =
  576. ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
  577. // Remove access qualifiers on images
  578. // (as they are inseparable from type in clang implementation,
  579. // but OpenCL spec provides a special query to get access qualifier
  580. // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
  581. if (ty->isImageType()) {
  582. removeImageAccessQualifier(typeName);
  583. removeImageAccessQualifier(baseTypeName);
  584. }
  585. argTypeNames.push_back(llvm::MDString::get(Context, typeName));
  586. // Turn "unsigned type" to "utype"
  587. pos = baseTypeName.find("unsigned");
  588. if (pos != std::string::npos)
  589. baseTypeName.erase(pos+1, 8);
  590. argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
  591. if (isPipe)
  592. typeQuals = "pipe";
  593. }
  594. argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals));
  595. // Get image and pipe access qualifier:
  596. if (ty->isImageType()|| ty->isPipeType()) {
  597. const Decl *PDecl = parm;
  598. if (auto *TD = dyn_cast<TypedefType>(ty))
  599. PDecl = TD->getDecl();
  600. const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
  601. if (A && A->isWriteOnly())
  602. accessQuals.push_back(llvm::MDString::get(Context, "write_only"));
  603. else if (A && A->isReadWrite())
  604. accessQuals.push_back(llvm::MDString::get(Context, "read_write"));
  605. else
  606. accessQuals.push_back(llvm::MDString::get(Context, "read_only"));
  607. } else
  608. accessQuals.push_back(llvm::MDString::get(Context, "none"));
  609. // Get argument name.
  610. argNames.push_back(llvm::MDString::get(Context, parm->getName()));
  611. }
  612. Fn->setMetadata("kernel_arg_addr_space",
  613. llvm::MDNode::get(Context, addressQuals));
  614. Fn->setMetadata("kernel_arg_access_qual",
  615. llvm::MDNode::get(Context, accessQuals));
  616. Fn->setMetadata("kernel_arg_type",
  617. llvm::MDNode::get(Context, argTypeNames));
  618. Fn->setMetadata("kernel_arg_base_type",
  619. llvm::MDNode::get(Context, argBaseTypeNames));
  620. Fn->setMetadata("kernel_arg_type_qual",
  621. llvm::MDNode::get(Context, argTypeQuals));
  622. if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
  623. Fn->setMetadata("kernel_arg_name",
  624. llvm::MDNode::get(Context, argNames));
  625. }
  626. void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
  627. llvm::Function *Fn)
  628. {
  629. if (!FD->hasAttr<OpenCLKernelAttr>())
  630. return;
  631. llvm::LLVMContext &Context = getLLVMContext();
  632. GenOpenCLArgMetadata(FD, Fn, CGM, Context, Builder, getContext());
  633. if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
  634. QualType HintQTy = A->getTypeHint();
  635. const ExtVectorType *HintEltQTy = HintQTy->getAs<ExtVectorType>();
  636. bool IsSignedInteger =
  637. HintQTy->isSignedIntegerType() ||
  638. (HintEltQTy && HintEltQTy->getElementType()->isSignedIntegerType());
  639. llvm::Metadata *AttrMDArgs[] = {
  640. llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
  641. CGM.getTypes().ConvertType(A->getTypeHint()))),
  642. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  643. llvm::IntegerType::get(Context, 32),
  644. llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))};
  645. Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs));
  646. }
  647. if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
  648. llvm::Metadata *AttrMDArgs[] = {
  649. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
  650. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
  651. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
  652. Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs));
  653. }
  654. if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
  655. llvm::Metadata *AttrMDArgs[] = {
  656. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
  657. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
  658. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
  659. Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs));
  660. }
  661. if (const OpenCLIntelReqdSubGroupSizeAttr *A =
  662. FD->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
  663. llvm::Metadata *AttrMDArgs[] = {
  664. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getSubGroupSize()))};
  665. Fn->setMetadata("intel_reqd_sub_group_size",
  666. llvm::MDNode::get(Context, AttrMDArgs));
  667. }
  668. }
  669. /// Determine whether the function F ends with a return stmt.
  670. static bool endsWithReturn(const Decl* F) {
  671. const Stmt *Body = nullptr;
  672. if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
  673. Body = FD->getBody();
  674. else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
  675. Body = OMD->getBody();
  676. if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
  677. auto LastStmt = CS->body_rbegin();
  678. if (LastStmt != CS->body_rend())
  679. return isa<ReturnStmt>(*LastStmt);
  680. }
  681. return false;
  682. }
  683. void CodeGenFunction::markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn) {
  684. if (SanOpts.has(SanitizerKind::Thread)) {
  685. Fn->addFnAttr("sanitize_thread_no_checking_at_run_time");
  686. Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
  687. }
  688. }
  689. static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx) {
  690. auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
  691. if (!MD || !MD->getDeclName().getAsIdentifierInfo() ||
  692. !MD->getDeclName().getAsIdentifierInfo()->isStr("allocate") ||
  693. (MD->getNumParams() != 1 && MD->getNumParams() != 2))
  694. return false;
  695. if (MD->parameters()[0]->getType().getCanonicalType() != Ctx.getSizeType())
  696. return false;
  697. if (MD->getNumParams() == 2) {
  698. auto *PT = MD->parameters()[1]->getType()->getAs<PointerType>();
  699. if (!PT || !PT->isVoidPointerType() ||
  700. !PT->getPointeeType().isConstQualified())
  701. return false;
  702. }
  703. return true;
  704. }
  705. /// Return the UBSan prologue signature for \p FD if one is available.
  706. static llvm::Constant *getPrologueSignature(CodeGenModule &CGM,
  707. const FunctionDecl *FD) {
  708. if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
  709. if (!MD->isStatic())
  710. return nullptr;
  711. return CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM);
  712. }
  713. void CodeGenFunction::StartFunction(GlobalDecl GD,
  714. QualType RetTy,
  715. llvm::Function *Fn,
  716. const CGFunctionInfo &FnInfo,
  717. const FunctionArgList &Args,
  718. SourceLocation Loc,
  719. SourceLocation StartLoc) {
  720. assert(!CurFn &&
  721. "Do not use a CodeGenFunction object for more than one function");
  722. const Decl *D = GD.getDecl();
  723. DidCallStackSave = false;
  724. CurCodeDecl = D;
  725. if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D))
  726. if (FD->usesSEHTry())
  727. CurSEHParent = FD;
  728. CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
  729. FnRetTy = RetTy;
  730. CurFn = Fn;
  731. CurFnInfo = &FnInfo;
  732. assert(CurFn->isDeclaration() && "Function already has body?");
  733. // If this function has been blacklisted for any of the enabled sanitizers,
  734. // disable the sanitizer for the function.
  735. do {
  736. #define SANITIZER(NAME, ID) \
  737. if (SanOpts.empty()) \
  738. break; \
  739. if (SanOpts.has(SanitizerKind::ID)) \
  740. if (CGM.isInSanitizerBlacklist(SanitizerKind::ID, Fn, Loc)) \
  741. SanOpts.set(SanitizerKind::ID, false);
  742. #include "clang/Basic/Sanitizers.def"
  743. #undef SANITIZER
  744. } while (0);
  745. if (D) {
  746. // Apply the no_sanitize* attributes to SanOpts.
  747. for (auto Attr : D->specific_attrs<NoSanitizeAttr>()) {
  748. SanitizerMask mask = Attr->getMask();
  749. SanOpts.Mask &= ~mask;
  750. if (mask & SanitizerKind::Address)
  751. SanOpts.set(SanitizerKind::KernelAddress, false);
  752. if (mask & SanitizerKind::KernelAddress)
  753. SanOpts.set(SanitizerKind::Address, false);
  754. if (mask & SanitizerKind::HWAddress)
  755. SanOpts.set(SanitizerKind::KernelHWAddress, false);
  756. if (mask & SanitizerKind::KernelHWAddress)
  757. SanOpts.set(SanitizerKind::HWAddress, false);
  758. }
  759. }
  760. // Apply sanitizer attributes to the function.
  761. if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
  762. Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
  763. if (SanOpts.hasOneOf(SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress))
  764. Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
  765. if (SanOpts.has(SanitizerKind::Thread))
  766. Fn->addFnAttr(llvm::Attribute::SanitizeThread);
  767. if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory))
  768. Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
  769. if (SanOpts.has(SanitizerKind::SafeStack))
  770. Fn->addFnAttr(llvm::Attribute::SafeStack);
  771. if (SanOpts.has(SanitizerKind::ShadowCallStack))
  772. Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
  773. // Apply fuzzing attribute to the function.
  774. if (SanOpts.hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink))
  775. Fn->addFnAttr(llvm::Attribute::OptForFuzzing);
  776. // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize,
  777. // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time.
  778. if (SanOpts.has(SanitizerKind::Thread)) {
  779. if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
  780. IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
  781. if (OMD->getMethodFamily() == OMF_dealloc ||
  782. OMD->getMethodFamily() == OMF_initialize ||
  783. (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) {
  784. markAsIgnoreThreadCheckingAtRuntime(Fn);
  785. }
  786. }
  787. }
  788. // Ignore unrelated casts in STL allocate() since the allocator must cast
  789. // from void* to T* before object initialization completes. Don't match on the
  790. // namespace because not all allocators are in std::
  791. if (D && SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
  792. if (matchesStlAllocatorFn(D, getContext()))
  793. SanOpts.Mask &= ~SanitizerKind::CFIUnrelatedCast;
  794. }
  795. // Apply xray attributes to the function (as a string, for now)
  796. if (D) {
  797. if (const auto *XRayAttr = D->getAttr<XRayInstrumentAttr>()) {
  798. if (CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
  799. XRayInstrKind::Function)) {
  800. if (XRayAttr->alwaysXRayInstrument() && ShouldXRayInstrumentFunction())
  801. Fn->addFnAttr("function-instrument", "xray-always");
  802. if (XRayAttr->neverXRayInstrument())
  803. Fn->addFnAttr("function-instrument", "xray-never");
  804. if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>())
  805. if (ShouldXRayInstrumentFunction())
  806. Fn->addFnAttr("xray-log-args",
  807. llvm::utostr(LogArgs->getArgumentCount()));
  808. }
  809. } else {
  810. if (ShouldXRayInstrumentFunction() && !CGM.imbueXRayAttrs(Fn, Loc))
  811. Fn->addFnAttr(
  812. "xray-instruction-threshold",
  813. llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
  814. }
  815. }
  816. // Add no-jump-tables value.
  817. Fn->addFnAttr("no-jump-tables",
  818. llvm::toStringRef(CGM.getCodeGenOpts().NoUseJumpTables));
  819. // Add profile-sample-accurate value.
  820. if (CGM.getCodeGenOpts().ProfileSampleAccurate)
  821. Fn->addFnAttr("profile-sample-accurate");
  822. if (getLangOpts().OpenCL) {
  823. // Add metadata for a kernel function.
  824. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  825. EmitOpenCLKernelMetadata(FD, Fn);
  826. }
  827. // If we are checking function types, emit a function type signature as
  828. // prologue data.
  829. if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
  830. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
  831. if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) {
  832. // Remove any (C++17) exception specifications, to allow calling e.g. a
  833. // noexcept function through a non-noexcept pointer.
  834. auto ProtoTy =
  835. getContext().getFunctionTypeWithExceptionSpec(FD->getType(),
  836. EST_None);
  837. llvm::Constant *FTRTTIConst =
  838. CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true);
  839. llvm::Constant *FTRTTIConstEncoded =
  840. EncodeAddrForUseInPrologue(Fn, FTRTTIConst);
  841. llvm::Constant *PrologueStructElems[] = {PrologueSig,
  842. FTRTTIConstEncoded};
  843. llvm::Constant *PrologueStructConst =
  844. llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
  845. Fn->setPrologueData(PrologueStructConst);
  846. }
  847. }
  848. }
  849. // If we're checking nullability, we need to know whether we can check the
  850. // return value. Initialize the flag to 'true' and refine it in EmitParmDecl.
  851. if (SanOpts.has(SanitizerKind::NullabilityReturn)) {
  852. auto Nullability = FnRetTy->getNullability(getContext());
  853. if (Nullability && *Nullability == NullabilityKind::NonNull) {
  854. if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
  855. CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>()))
  856. RetValNullabilityPrecondition =
  857. llvm::ConstantInt::getTrue(getLLVMContext());
  858. }
  859. }
  860. // If we're in C++ mode and the function name is "main", it is guaranteed
  861. // to be norecurse by the standard (3.6.1.3 "The function main shall not be
  862. // used within a program").
  863. if (getLangOpts().CPlusPlus)
  864. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  865. if (FD->isMain())
  866. Fn->addFnAttr(llvm::Attribute::NoRecurse);
  867. // If a custom alignment is used, force realigning to this alignment on
  868. // any main function which certainly will need it.
  869. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  870. if ((FD->isMain() || FD->isMSVCRTEntryPoint()) &&
  871. CGM.getCodeGenOpts().StackAlignment)
  872. Fn->addFnAttr("stackrealign");
  873. llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
  874. // Create a marker to make it easy to insert allocas into the entryblock
  875. // later. Don't create this with the builder, because we don't want it
  876. // folded.
  877. llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
  878. AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB);
  879. ReturnBlock = getJumpDestInCurrentScope("return");
  880. Builder.SetInsertPoint(EntryBB);
  881. // If we're checking the return value, allocate space for a pointer to a
  882. // precise source location of the checked return statement.
  883. if (requiresReturnValueCheck()) {
  884. ReturnLocation = CreateDefaultAlignTempAlloca(Int8PtrTy, "return.sloc.ptr");
  885. InitTempAlloca(ReturnLocation, llvm::ConstantPointerNull::get(Int8PtrTy));
  886. }
  887. // Emit subprogram debug descriptor.
  888. if (CGDebugInfo *DI = getDebugInfo()) {
  889. // Reconstruct the type from the argument list so that implicit parameters,
  890. // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
  891. // convention.
  892. CallingConv CC = CallingConv::CC_C;
  893. if (auto *FD = dyn_cast_or_null<FunctionDecl>(D))
  894. if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
  895. CC = SrcFnTy->getCallConv();
  896. SmallVector<QualType, 16> ArgTypes;
  897. for (const VarDecl *VD : Args)
  898. ArgTypes.push_back(VD->getType());
  899. QualType FnType = getContext().getFunctionType(
  900. RetTy, ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
  901. DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, CurFuncIsThunk,
  902. Builder);
  903. }
  904. if (ShouldInstrumentFunction()) {
  905. if (CGM.getCodeGenOpts().InstrumentFunctions)
  906. CurFn->addFnAttr("instrument-function-entry", "__cyg_profile_func_enter");
  907. if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
  908. CurFn->addFnAttr("instrument-function-entry-inlined",
  909. "__cyg_profile_func_enter");
  910. if (CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
  911. CurFn->addFnAttr("instrument-function-entry-inlined",
  912. "__cyg_profile_func_enter_bare");
  913. }
  914. // Since emitting the mcount call here impacts optimizations such as function
  915. // inlining, we just add an attribute to insert a mcount call in backend.
  916. // The attribute "counting-function" is set to mcount function name which is
  917. // architecture dependent.
  918. if (CGM.getCodeGenOpts().InstrumentForProfiling) {
  919. // Calls to fentry/mcount should not be generated if function has
  920. // the no_instrument_function attribute.
  921. if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) {
  922. if (CGM.getCodeGenOpts().CallFEntry)
  923. Fn->addFnAttr("fentry-call", "true");
  924. else {
  925. Fn->addFnAttr("instrument-function-entry-inlined",
  926. getTarget().getMCountName());
  927. }
  928. }
  929. }
  930. if (RetTy->isVoidType()) {
  931. // Void type; nothing to return.
  932. ReturnValue = Address::invalid();
  933. // Count the implicit return.
  934. if (!endsWithReturn(D))
  935. ++NumReturnExprs;
  936. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
  937. !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
  938. // Indirect aggregate return; emit returned value directly into sret slot.
  939. // This reduces code size, and affects correctness in C++.
  940. auto AI = CurFn->arg_begin();
  941. if (CurFnInfo->getReturnInfo().isSRetAfterThis())
  942. ++AI;
  943. ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign());
  944. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
  945. !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
  946. // Load the sret pointer from the argument struct and return into that.
  947. unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
  948. llvm::Function::arg_iterator EI = CurFn->arg_end();
  949. --EI;
  950. llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx);
  951. Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result");
  952. ReturnValue = Address(Addr, getNaturalTypeAlignment(RetTy));
  953. } else {
  954. ReturnValue = CreateIRTemp(RetTy, "retval");
  955. // Tell the epilog emitter to autorelease the result. We do this
  956. // now so that various specialized functions can suppress it
  957. // during their IR-generation.
  958. if (getLangOpts().ObjCAutoRefCount &&
  959. !CurFnInfo->isReturnsRetained() &&
  960. RetTy->isObjCRetainableType())
  961. AutoreleaseResult = true;
  962. }
  963. EmitStartEHSpec(CurCodeDecl);
  964. PrologueCleanupDepth = EHStack.stable_begin();
  965. // Emit OpenMP specific initialization of the device functions.
  966. if (getLangOpts().OpenMP && CurCodeDecl)
  967. CGM.getOpenMPRuntime().emitFunctionProlog(*this, CurCodeDecl);
  968. EmitFunctionProlog(*CurFnInfo, CurFn, Args);
  969. if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
  970. CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
  971. const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
  972. if (MD->getParent()->isLambda() &&
  973. MD->getOverloadedOperator() == OO_Call) {
  974. // We're in a lambda; figure out the captures.
  975. MD->getParent()->getCaptureFields(LambdaCaptureFields,
  976. LambdaThisCaptureField);
  977. if (LambdaThisCaptureField) {
  978. // If the lambda captures the object referred to by '*this' - either by
  979. // value or by reference, make sure CXXThisValue points to the correct
  980. // object.
  981. // Get the lvalue for the field (which is a copy of the enclosing object
  982. // or contains the address of the enclosing object).
  983. LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
  984. if (!LambdaThisCaptureField->getType()->isPointerType()) {
  985. // If the enclosing object was captured by value, just use its address.
  986. CXXThisValue = ThisFieldLValue.getAddress().getPointer();
  987. } else {
  988. // Load the lvalue pointed to by the field, since '*this' was captured
  989. // by reference.
  990. CXXThisValue =
  991. EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
  992. }
  993. }
  994. for (auto *FD : MD->getParent()->fields()) {
  995. if (FD->hasCapturedVLAType()) {
  996. auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
  997. SourceLocation()).getScalarVal();
  998. auto VAT = FD->getCapturedVLAType();
  999. VLASizeMap[VAT->getSizeExpr()] = ExprArg;
  1000. }
  1001. }
  1002. } else {
  1003. // Not in a lambda; just use 'this' from the method.
  1004. // FIXME: Should we generate a new load for each use of 'this'? The
  1005. // fast register allocator would be happier...
  1006. CXXThisValue = CXXABIThisValue;
  1007. }
  1008. // Check the 'this' pointer once per function, if it's available.
  1009. if (CXXABIThisValue) {
  1010. SanitizerSet SkippedChecks;
  1011. SkippedChecks.set(SanitizerKind::ObjectSize, true);
  1012. QualType ThisTy = MD->getThisType(getContext());
  1013. // If this is the call operator of a lambda with no capture-default, it
  1014. // may have a static invoker function, which may call this operator with
  1015. // a null 'this' pointer.
  1016. if (isLambdaCallOperator(MD) &&
  1017. MD->getParent()->getLambdaCaptureDefault() == LCD_None)
  1018. SkippedChecks.set(SanitizerKind::Null, true);
  1019. EmitTypeCheck(isa<CXXConstructorDecl>(MD) ? TCK_ConstructorCall
  1020. : TCK_MemberCall,
  1021. Loc, CXXABIThisValue, ThisTy,
  1022. getContext().getTypeAlignInChars(ThisTy->getPointeeType()),
  1023. SkippedChecks);
  1024. }
  1025. }
  1026. // If any of the arguments have a variably modified type, make sure to
  1027. // emit the type size.
  1028. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
  1029. i != e; ++i) {
  1030. const VarDecl *VD = *i;
  1031. // Dig out the type as written from ParmVarDecls; it's unclear whether
  1032. // the standard (C99 6.9.1p10) requires this, but we're following the
  1033. // precedent set by gcc.
  1034. QualType Ty;
  1035. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
  1036. Ty = PVD->getOriginalType();
  1037. else
  1038. Ty = VD->getType();
  1039. if (Ty->isVariablyModifiedType())
  1040. EmitVariablyModifiedType(Ty);
  1041. }
  1042. // Emit a location at the end of the prologue.
  1043. if (CGDebugInfo *DI = getDebugInfo())
  1044. DI->EmitLocation(Builder, StartLoc);
  1045. // TODO: Do we need to handle this in two places like we do with
  1046. // target-features/target-cpu?
  1047. if (CurFuncDecl)
  1048. if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>())
  1049. LargestVectorWidth = VecWidth->getVectorWidth();
  1050. }
  1051. void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args,
  1052. const Stmt *Body) {
  1053. incrementProfileCounter(Body);
  1054. if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
  1055. EmitCompoundStmtWithoutScope(*S);
  1056. else
  1057. EmitStmt(Body);
  1058. }
  1059. /// When instrumenting to collect profile data, the counts for some blocks
  1060. /// such as switch cases need to not include the fall-through counts, so
  1061. /// emit a branch around the instrumentation code. When not instrumenting,
  1062. /// this just calls EmitBlock().
  1063. void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
  1064. const Stmt *S) {
  1065. llvm::BasicBlock *SkipCountBB = nullptr;
  1066. if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) {
  1067. // When instrumenting for profiling, the fallthrough to certain
  1068. // statements needs to skip over the instrumentation code so that we
  1069. // get an accurate count.
  1070. SkipCountBB = createBasicBlock("skipcount");
  1071. EmitBranch(SkipCountBB);
  1072. }
  1073. EmitBlock(BB);
  1074. uint64_t CurrentCount = getCurrentProfileCount();
  1075. incrementProfileCounter(S);
  1076. setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
  1077. if (SkipCountBB)
  1078. EmitBlock(SkipCountBB);
  1079. }
  1080. /// Tries to mark the given function nounwind based on the
  1081. /// non-existence of any throwing calls within it. We believe this is
  1082. /// lightweight enough to do at -O0.
  1083. static void TryMarkNoThrow(llvm::Function *F) {
  1084. // LLVM treats 'nounwind' on a function as part of the type, so we
  1085. // can't do this on functions that can be overwritten.
  1086. if (F->isInterposable()) return;
  1087. for (llvm::BasicBlock &BB : *F)
  1088. for (llvm::Instruction &I : BB)
  1089. if (I.mayThrow())
  1090. return;
  1091. F->setDoesNotThrow();
  1092. }
  1093. QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
  1094. FunctionArgList &Args) {
  1095. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  1096. QualType ResTy = FD->getReturnType();
  1097. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  1098. if (MD && MD->isInstance()) {
  1099. if (CGM.getCXXABI().HasThisReturn(GD))
  1100. ResTy = MD->getThisType(getContext());
  1101. else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
  1102. ResTy = CGM.getContext().VoidPtrTy;
  1103. CGM.getCXXABI().buildThisParam(*this, Args);
  1104. }
  1105. // The base version of an inheriting constructor whose constructed base is a
  1106. // virtual base is not passed any arguments (because it doesn't actually call
  1107. // the inherited constructor).
  1108. bool PassedParams = true;
  1109. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
  1110. if (auto Inherited = CD->getInheritedConstructor())
  1111. PassedParams =
  1112. getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
  1113. if (PassedParams) {
  1114. for (auto *Param : FD->parameters()) {
  1115. Args.push_back(Param);
  1116. if (!Param->hasAttr<PassObjectSizeAttr>())
  1117. continue;
  1118. auto *Implicit = ImplicitParamDecl::Create(
  1119. getContext(), Param->getDeclContext(), Param->getLocation(),
  1120. /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamDecl::Other);
  1121. SizeArguments[Param] = Implicit;
  1122. Args.push_back(Implicit);
  1123. }
  1124. }
  1125. if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
  1126. CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
  1127. return ResTy;
  1128. }
  1129. static bool
  1130. shouldUseUndefinedBehaviorReturnOptimization(const FunctionDecl *FD,
  1131. const ASTContext &Context) {
  1132. QualType T = FD->getReturnType();
  1133. // Avoid the optimization for functions that return a record type with a
  1134. // trivial destructor or another trivially copyable type.
  1135. if (const RecordType *RT = T.getCanonicalType()->getAs<RecordType>()) {
  1136. if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
  1137. return !ClassDecl->hasTrivialDestructor();
  1138. }
  1139. return !T.isTriviallyCopyableType(Context);
  1140. }
  1141. void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
  1142. const CGFunctionInfo &FnInfo) {
  1143. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  1144. CurGD = GD;
  1145. FunctionArgList Args;
  1146. QualType ResTy = BuildFunctionArgList(GD, Args);
  1147. // Check if we should generate debug info for this function.
  1148. if (FD->hasAttr<NoDebugAttr>())
  1149. DebugInfo = nullptr; // disable debug info indefinitely for this function
  1150. // The function might not have a body if we're generating thunks for a
  1151. // function declaration.
  1152. SourceRange BodyRange;
  1153. if (Stmt *Body = FD->getBody())
  1154. BodyRange = Body->getSourceRange();
  1155. else
  1156. BodyRange = FD->getLocation();
  1157. CurEHLocation = BodyRange.getEnd();
  1158. // Use the location of the start of the function to determine where
  1159. // the function definition is located. By default use the location
  1160. // of the declaration as the location for the subprogram. A function
  1161. // may lack a declaration in the source code if it is created by code
  1162. // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
  1163. SourceLocation Loc = FD->getLocation();
  1164. // If this is a function specialization then use the pattern body
  1165. // as the location for the function.
  1166. if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
  1167. if (SpecDecl->hasBody(SpecDecl))
  1168. Loc = SpecDecl->getLocation();
  1169. Stmt *Body = FD->getBody();
  1170. // Initialize helper which will detect jumps which can cause invalid lifetime
  1171. // markers.
  1172. if (Body && ShouldEmitLifetimeMarkers)
  1173. Bypasses.Init(Body);
  1174. // Emit the standard function prologue.
  1175. StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
  1176. // Generate the body of the function.
  1177. PGO.assignRegionCounters(GD, CurFn);
  1178. if (isa<CXXDestructorDecl>(FD))
  1179. EmitDestructorBody(Args);
  1180. else if (isa<CXXConstructorDecl>(FD))
  1181. EmitConstructorBody(Args);
  1182. else if (getLangOpts().CUDA &&
  1183. !getLangOpts().CUDAIsDevice &&
  1184. FD->hasAttr<CUDAGlobalAttr>())
  1185. CGM.getCUDARuntime().emitDeviceStub(*this, Args);
  1186. else if (isa<CXXMethodDecl>(FD) &&
  1187. cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
  1188. // The lambda static invoker function is special, because it forwards or
  1189. // clones the body of the function call operator (but is actually static).
  1190. EmitLambdaStaticInvokeBody(cast<CXXMethodDecl>(FD));
  1191. } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
  1192. (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
  1193. cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
  1194. // Implicit copy-assignment gets the same special treatment as implicit
  1195. // copy-constructors.
  1196. emitImplicitAssignmentOperatorBody(Args);
  1197. } else if (Body) {
  1198. EmitFunctionBody(Args, Body);
  1199. } else
  1200. llvm_unreachable("no definition for emitted function");
  1201. // C++11 [stmt.return]p2:
  1202. // Flowing off the end of a function [...] results in undefined behavior in
  1203. // a value-returning function.
  1204. // C11 6.9.1p12:
  1205. // If the '}' that terminates a function is reached, and the value of the
  1206. // function call is used by the caller, the behavior is undefined.
  1207. if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
  1208. !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
  1209. bool ShouldEmitUnreachable =
  1210. CGM.getCodeGenOpts().StrictReturn ||
  1211. shouldUseUndefinedBehaviorReturnOptimization(FD, getContext());
  1212. if (SanOpts.has(SanitizerKind::Return)) {
  1213. SanitizerScope SanScope(this);
  1214. llvm::Value *IsFalse = Builder.getFalse();
  1215. EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
  1216. SanitizerHandler::MissingReturn,
  1217. EmitCheckSourceLocation(FD->getLocation()), None);
  1218. } else if (ShouldEmitUnreachable) {
  1219. if (CGM.getCodeGenOpts().OptimizationLevel == 0)
  1220. EmitTrapCall(llvm::Intrinsic::trap);
  1221. }
  1222. if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) {
  1223. Builder.CreateUnreachable();
  1224. Builder.ClearInsertionPoint();
  1225. }
  1226. }
  1227. // Emit the standard function epilogue.
  1228. FinishFunction(BodyRange.getEnd());
  1229. // If we haven't marked the function nothrow through other means, do
  1230. // a quick pass now to see if we can.
  1231. if (!CurFn->doesNotThrow())
  1232. TryMarkNoThrow(CurFn);
  1233. }
  1234. /// ContainsLabel - Return true if the statement contains a label in it. If
  1235. /// this statement is not executed normally, it not containing a label means
  1236. /// that we can just remove the code.
  1237. bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
  1238. // Null statement, not a label!
  1239. if (!S) return false;
  1240. // If this is a label, we have to emit the code, consider something like:
  1241. // if (0) { ... foo: bar(); } goto foo;
  1242. //
  1243. // TODO: If anyone cared, we could track __label__'s, since we know that you
  1244. // can't jump to one from outside their declared region.
  1245. if (isa<LabelStmt>(S))
  1246. return true;
  1247. // If this is a case/default statement, and we haven't seen a switch, we have
  1248. // to emit the code.
  1249. if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
  1250. return true;
  1251. // If this is a switch statement, we want to ignore cases below it.
  1252. if (isa<SwitchStmt>(S))
  1253. IgnoreCaseStmts = true;
  1254. // Scan subexpressions for verboten labels.
  1255. for (const Stmt *SubStmt : S->children())
  1256. if (ContainsLabel(SubStmt, IgnoreCaseStmts))
  1257. return true;
  1258. return false;
  1259. }
  1260. /// containsBreak - Return true if the statement contains a break out of it.
  1261. /// If the statement (recursively) contains a switch or loop with a break
  1262. /// inside of it, this is fine.
  1263. bool CodeGenFunction::containsBreak(const Stmt *S) {
  1264. // Null statement, not a label!
  1265. if (!S) return false;
  1266. // If this is a switch or loop that defines its own break scope, then we can
  1267. // include it and anything inside of it.
  1268. if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
  1269. isa<ForStmt>(S))
  1270. return false;
  1271. if (isa<BreakStmt>(S))
  1272. return true;
  1273. // Scan subexpressions for verboten breaks.
  1274. for (const Stmt *SubStmt : S->children())
  1275. if (containsBreak(SubStmt))
  1276. return true;
  1277. return false;
  1278. }
  1279. bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) {
  1280. if (!S) return false;
  1281. // Some statement kinds add a scope and thus never add a decl to the current
  1282. // scope. Note, this list is longer than the list of statements that might
  1283. // have an unscoped decl nested within them, but this way is conservatively
  1284. // correct even if more statement kinds are added.
  1285. if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
  1286. isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) ||
  1287. isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) ||
  1288. isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S))
  1289. return false;
  1290. if (isa<DeclStmt>(S))
  1291. return true;
  1292. for (const Stmt *SubStmt : S->children())
  1293. if (mightAddDeclToScope(SubStmt))
  1294. return true;
  1295. return false;
  1296. }
  1297. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  1298. /// to a constant, or if it does but contains a label, return false. If it
  1299. /// constant folds return true and set the boolean result in Result.
  1300. bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
  1301. bool &ResultBool,
  1302. bool AllowLabels) {
  1303. llvm::APSInt ResultInt;
  1304. if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
  1305. return false;
  1306. ResultBool = ResultInt.getBoolValue();
  1307. return true;
  1308. }
  1309. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  1310. /// to a constant, or if it does but contains a label, return false. If it
  1311. /// constant folds return true and set the folded value.
  1312. bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
  1313. llvm::APSInt &ResultInt,
  1314. bool AllowLabels) {
  1315. // FIXME: Rename and handle conversion of other evaluatable things
  1316. // to bool.
  1317. llvm::APSInt Int;
  1318. if (!Cond->EvaluateAsInt(Int, getContext()))
  1319. return false; // Not foldable, not integer or not fully evaluatable.
  1320. if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
  1321. return false; // Contains a label.
  1322. ResultInt = Int;
  1323. return true;
  1324. }
  1325. /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
  1326. /// statement) to the specified blocks. Based on the condition, this might try
  1327. /// to simplify the codegen of the conditional based on the branch.
  1328. ///
  1329. void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
  1330. llvm::BasicBlock *TrueBlock,
  1331. llvm::BasicBlock *FalseBlock,
  1332. uint64_t TrueCount) {
  1333. Cond = Cond->IgnoreParens();
  1334. if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
  1335. // Handle X && Y in a condition.
  1336. if (CondBOp->getOpcode() == BO_LAnd) {
  1337. // If we have "1 && X", simplify the code. "0 && X" would have constant
  1338. // folded if the case was simple enough.
  1339. bool ConstantBool = false;
  1340. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  1341. ConstantBool) {
  1342. // br(1 && X) -> br(X).
  1343. incrementProfileCounter(CondBOp);
  1344. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
  1345. TrueCount);
  1346. }
  1347. // If we have "X && 1", simplify the code to use an uncond branch.
  1348. // "X && 0" would have been constant folded to 0.
  1349. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  1350. ConstantBool) {
  1351. // br(X && 1) -> br(X).
  1352. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
  1353. TrueCount);
  1354. }
  1355. // Emit the LHS as a conditional. If the LHS conditional is false, we
  1356. // want to jump to the FalseBlock.
  1357. llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
  1358. // The counter tells us how often we evaluate RHS, and all of TrueCount
  1359. // can be propagated to that branch.
  1360. uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
  1361. ConditionalEvaluation eval(*this);
  1362. {
  1363. ApplyDebugLocation DL(*this, Cond);
  1364. EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
  1365. EmitBlock(LHSTrue);
  1366. }
  1367. incrementProfileCounter(CondBOp);
  1368. setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
  1369. // Any temporaries created here are conditional.
  1370. eval.begin(*this);
  1371. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount);
  1372. eval.end(*this);
  1373. return;
  1374. }
  1375. if (CondBOp->getOpcode() == BO_LOr) {
  1376. // If we have "0 || X", simplify the code. "1 || X" would have constant
  1377. // folded if the case was simple enough.
  1378. bool ConstantBool = false;
  1379. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  1380. !ConstantBool) {
  1381. // br(0 || X) -> br(X).
  1382. incrementProfileCounter(CondBOp);
  1383. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
  1384. TrueCount);
  1385. }
  1386. // If we have "X || 0", simplify the code to use an uncond branch.
  1387. // "X || 1" would have been constant folded to 1.
  1388. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  1389. !ConstantBool) {
  1390. // br(X || 0) -> br(X).
  1391. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
  1392. TrueCount);
  1393. }
  1394. // Emit the LHS as a conditional. If the LHS conditional is true, we
  1395. // want to jump to the TrueBlock.
  1396. llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
  1397. // We have the count for entry to the RHS and for the whole expression
  1398. // being true, so we can divy up True count between the short circuit and
  1399. // the RHS.
  1400. uint64_t LHSCount =
  1401. getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
  1402. uint64_t RHSCount = TrueCount - LHSCount;
  1403. ConditionalEvaluation eval(*this);
  1404. {
  1405. ApplyDebugLocation DL(*this, Cond);
  1406. EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
  1407. EmitBlock(LHSFalse);
  1408. }
  1409. incrementProfileCounter(CondBOp);
  1410. setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
  1411. // Any temporaries created here are conditional.
  1412. eval.begin(*this);
  1413. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount);
  1414. eval.end(*this);
  1415. return;
  1416. }
  1417. }
  1418. if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
  1419. // br(!x, t, f) -> br(x, f, t)
  1420. if (CondUOp->getOpcode() == UO_LNot) {
  1421. // Negate the count.
  1422. uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
  1423. // Negate the condition and swap the destination blocks.
  1424. return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
  1425. FalseCount);
  1426. }
  1427. }
  1428. if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
  1429. // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
  1430. llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
  1431. llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
  1432. ConditionalEvaluation cond(*this);
  1433. EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
  1434. getProfileCount(CondOp));
  1435. // When computing PGO branch weights, we only know the overall count for
  1436. // the true block. This code is essentially doing tail duplication of the
  1437. // naive code-gen, introducing new edges for which counts are not
  1438. // available. Divide the counts proportionally between the LHS and RHS of
  1439. // the conditional operator.
  1440. uint64_t LHSScaledTrueCount = 0;
  1441. if (TrueCount) {
  1442. double LHSRatio =
  1443. getProfileCount(CondOp) / (double)getCurrentProfileCount();
  1444. LHSScaledTrueCount = TrueCount * LHSRatio;
  1445. }
  1446. cond.begin(*this);
  1447. EmitBlock(LHSBlock);
  1448. incrementProfileCounter(CondOp);
  1449. {
  1450. ApplyDebugLocation DL(*this, Cond);
  1451. EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
  1452. LHSScaledTrueCount);
  1453. }
  1454. cond.end(*this);
  1455. cond.begin(*this);
  1456. EmitBlock(RHSBlock);
  1457. EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
  1458. TrueCount - LHSScaledTrueCount);
  1459. cond.end(*this);
  1460. return;
  1461. }
  1462. if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
  1463. // Conditional operator handling can give us a throw expression as a
  1464. // condition for a case like:
  1465. // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
  1466. // Fold this to:
  1467. // br(c, throw x, br(y, t, f))
  1468. EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
  1469. return;
  1470. }
  1471. // If the branch has a condition wrapped by __builtin_unpredictable,
  1472. // create metadata that specifies that the branch is unpredictable.
  1473. // Don't bother if not optimizing because that metadata would not be used.
  1474. llvm::MDNode *Unpredictable = nullptr;
  1475. auto *Call = dyn_cast<CallExpr>(Cond);
  1476. if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
  1477. auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
  1478. if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
  1479. llvm::MDBuilder MDHelper(getLLVMContext());
  1480. Unpredictable = MDHelper.createUnpredictable();
  1481. }
  1482. }
  1483. // Create branch weights based on the number of times we get here and the
  1484. // number of times the condition should be true.
  1485. uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
  1486. llvm::MDNode *Weights =
  1487. createProfileWeights(TrueCount, CurrentCount - TrueCount);
  1488. // Emit the code with the fully general case.
  1489. llvm::Value *CondV;
  1490. {
  1491. ApplyDebugLocation DL(*this, Cond);
  1492. CondV = EvaluateExprAsBool(Cond);
  1493. }
  1494. Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
  1495. }
  1496. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  1497. /// specified stmt yet.
  1498. void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
  1499. CGM.ErrorUnsupported(S, Type);
  1500. }
  1501. /// emitNonZeroVLAInit - Emit the "zero" initialization of a
  1502. /// variable-length array whose elements have a non-zero bit-pattern.
  1503. ///
  1504. /// \param baseType the inner-most element type of the array
  1505. /// \param src - a char* pointing to the bit-pattern for a single
  1506. /// base element of the array
  1507. /// \param sizeInChars - the total size of the VLA, in chars
  1508. static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
  1509. Address dest, Address src,
  1510. llvm::Value *sizeInChars) {
  1511. CGBuilderTy &Builder = CGF.Builder;
  1512. CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
  1513. llvm::Value *baseSizeInChars
  1514. = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
  1515. Address begin =
  1516. Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin");
  1517. llvm::Value *end =
  1518. Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars, "vla.end");
  1519. llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
  1520. llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
  1521. llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
  1522. // Make a loop over the VLA. C99 guarantees that the VLA element
  1523. // count must be nonzero.
  1524. CGF.EmitBlock(loopBB);
  1525. llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
  1526. cur->addIncoming(begin.getPointer(), originBB);
  1527. CharUnits curAlign =
  1528. dest.getAlignment().alignmentOfArrayElement(baseSize);
  1529. // memcpy the individual element bit-pattern.
  1530. Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars,
  1531. /*volatile*/ false);
  1532. // Go to the next element.
  1533. llvm::Value *next =
  1534. Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
  1535. // Leave if that's the end of the VLA.
  1536. llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
  1537. Builder.CreateCondBr(done, contBB, loopBB);
  1538. cur->addIncoming(next, loopBB);
  1539. CGF.EmitBlock(contBB);
  1540. }
  1541. void
  1542. CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
  1543. // Ignore empty classes in C++.
  1544. if (getLangOpts().CPlusPlus) {
  1545. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  1546. if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
  1547. return;
  1548. }
  1549. }
  1550. // Cast the dest ptr to the appropriate i8 pointer type.
  1551. if (DestPtr.getElementType() != Int8Ty)
  1552. DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
  1553. // Get size and alignment info for this aggregate.
  1554. CharUnits size = getContext().getTypeSizeInChars(Ty);
  1555. llvm::Value *SizeVal;
  1556. const VariableArrayType *vla;
  1557. // Don't bother emitting a zero-byte memset.
  1558. if (size.isZero()) {
  1559. // But note that getTypeInfo returns 0 for a VLA.
  1560. if (const VariableArrayType *vlaType =
  1561. dyn_cast_or_null<VariableArrayType>(
  1562. getContext().getAsArrayType(Ty))) {
  1563. auto VlaSize = getVLASize(vlaType);
  1564. SizeVal = VlaSize.NumElts;
  1565. CharUnits eltSize = getContext().getTypeSizeInChars(VlaSize.Type);
  1566. if (!eltSize.isOne())
  1567. SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
  1568. vla = vlaType;
  1569. } else {
  1570. return;
  1571. }
  1572. } else {
  1573. SizeVal = CGM.getSize(size);
  1574. vla = nullptr;
  1575. }
  1576. // If the type contains a pointer to data member we can't memset it to zero.
  1577. // Instead, create a null constant and copy it to the destination.
  1578. // TODO: there are other patterns besides zero that we can usefully memset,
  1579. // like -1, which happens to be the pattern used by member-pointers.
  1580. if (!CGM.getTypes().isZeroInitializable(Ty)) {
  1581. // For a VLA, emit a single element, then splat that over the VLA.
  1582. if (vla) Ty = getContext().getBaseElementType(vla);
  1583. llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
  1584. llvm::GlobalVariable *NullVariable =
  1585. new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
  1586. /*isConstant=*/true,
  1587. llvm::GlobalVariable::PrivateLinkage,
  1588. NullConstant, Twine());
  1589. CharUnits NullAlign = DestPtr.getAlignment();
  1590. NullVariable->setAlignment(NullAlign.getQuantity());
  1591. Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()),
  1592. NullAlign);
  1593. if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
  1594. // Get and call the appropriate llvm.memcpy overload.
  1595. Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
  1596. return;
  1597. }
  1598. // Otherwise, just memset the whole thing to zero. This is legal
  1599. // because in LLVM, all default initializers (other than the ones we just
  1600. // handled above) are guaranteed to have a bit pattern of all zeros.
  1601. Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
  1602. }
  1603. llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
  1604. // Make sure that there is a block for the indirect goto.
  1605. if (!IndirectBranch)
  1606. GetIndirectGotoBlock();
  1607. llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
  1608. // Make sure the indirect branch includes all of the address-taken blocks.
  1609. IndirectBranch->addDestination(BB);
  1610. return llvm::BlockAddress::get(CurFn, BB);
  1611. }
  1612. llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
  1613. // If we already made the indirect branch for indirect goto, return its block.
  1614. if (IndirectBranch) return IndirectBranch->getParent();
  1615. CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
  1616. // Create the PHI node that indirect gotos will add entries to.
  1617. llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
  1618. "indirect.goto.dest");
  1619. // Create the indirect branch instruction.
  1620. IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
  1621. return IndirectBranch->getParent();
  1622. }
  1623. /// Computes the length of an array in elements, as well as the base
  1624. /// element type and a properly-typed first element pointer.
  1625. llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
  1626. QualType &baseType,
  1627. Address &addr) {
  1628. const ArrayType *arrayType = origArrayType;
  1629. // If it's a VLA, we have to load the stored size. Note that
  1630. // this is the size of the VLA in bytes, not its size in elements.
  1631. llvm::Value *numVLAElements = nullptr;
  1632. if (isa<VariableArrayType>(arrayType)) {
  1633. numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).NumElts;
  1634. // Walk into all VLAs. This doesn't require changes to addr,
  1635. // which has type T* where T is the first non-VLA element type.
  1636. do {
  1637. QualType elementType = arrayType->getElementType();
  1638. arrayType = getContext().getAsArrayType(elementType);
  1639. // If we only have VLA components, 'addr' requires no adjustment.
  1640. if (!arrayType) {
  1641. baseType = elementType;
  1642. return numVLAElements;
  1643. }
  1644. } while (isa<VariableArrayType>(arrayType));
  1645. // We get out here only if we find a constant array type
  1646. // inside the VLA.
  1647. }
  1648. // We have some number of constant-length arrays, so addr should
  1649. // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
  1650. // down to the first element of addr.
  1651. SmallVector<llvm::Value*, 8> gepIndices;
  1652. // GEP down to the array type.
  1653. llvm::ConstantInt *zero = Builder.getInt32(0);
  1654. gepIndices.push_back(zero);
  1655. uint64_t countFromCLAs = 1;
  1656. QualType eltType;
  1657. llvm::ArrayType *llvmArrayType =
  1658. dyn_cast<llvm::ArrayType>(addr.getElementType());
  1659. while (llvmArrayType) {
  1660. assert(isa<ConstantArrayType>(arrayType));
  1661. assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
  1662. == llvmArrayType->getNumElements());
  1663. gepIndices.push_back(zero);
  1664. countFromCLAs *= llvmArrayType->getNumElements();
  1665. eltType = arrayType->getElementType();
  1666. llvmArrayType =
  1667. dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
  1668. arrayType = getContext().getAsArrayType(arrayType->getElementType());
  1669. assert((!llvmArrayType || arrayType) &&
  1670. "LLVM and Clang types are out-of-synch");
  1671. }
  1672. if (arrayType) {
  1673. // From this point onwards, the Clang array type has been emitted
  1674. // as some other type (probably a packed struct). Compute the array
  1675. // size, and just emit the 'begin' expression as a bitcast.
  1676. while (arrayType) {
  1677. countFromCLAs *=
  1678. cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
  1679. eltType = arrayType->getElementType();
  1680. arrayType = getContext().getAsArrayType(eltType);
  1681. }
  1682. llvm::Type *baseType = ConvertType(eltType);
  1683. addr = Builder.CreateElementBitCast(addr, baseType, "array.begin");
  1684. } else {
  1685. // Create the actual GEP.
  1686. addr = Address(Builder.CreateInBoundsGEP(addr.getPointer(),
  1687. gepIndices, "array.begin"),
  1688. addr.getAlignment());
  1689. }
  1690. baseType = eltType;
  1691. llvm::Value *numElements
  1692. = llvm::ConstantInt::get(SizeTy, countFromCLAs);
  1693. // If we had any VLA dimensions, factor them in.
  1694. if (numVLAElements)
  1695. numElements = Builder.CreateNUWMul(numVLAElements, numElements);
  1696. return numElements;
  1697. }
  1698. CodeGenFunction::VlaSizePair CodeGenFunction::getVLASize(QualType type) {
  1699. const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
  1700. assert(vla && "type was not a variable array type!");
  1701. return getVLASize(vla);
  1702. }
  1703. CodeGenFunction::VlaSizePair
  1704. CodeGenFunction::getVLASize(const VariableArrayType *type) {
  1705. // The number of elements so far; always size_t.
  1706. llvm::Value *numElements = nullptr;
  1707. QualType elementType;
  1708. do {
  1709. elementType = type->getElementType();
  1710. llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
  1711. assert(vlaSize && "no size for VLA!");
  1712. assert(vlaSize->getType() == SizeTy);
  1713. if (!numElements) {
  1714. numElements = vlaSize;
  1715. } else {
  1716. // It's undefined behavior if this wraps around, so mark it that way.
  1717. // FIXME: Teach -fsanitize=undefined to trap this.
  1718. numElements = Builder.CreateNUWMul(numElements, vlaSize);
  1719. }
  1720. } while ((type = getContext().getAsVariableArrayType(elementType)));
  1721. return { numElements, elementType };
  1722. }
  1723. CodeGenFunction::VlaSizePair
  1724. CodeGenFunction::getVLAElements1D(QualType type) {
  1725. const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
  1726. assert(vla && "type was not a variable array type!");
  1727. return getVLAElements1D(vla);
  1728. }
  1729. CodeGenFunction::VlaSizePair
  1730. CodeGenFunction::getVLAElements1D(const VariableArrayType *Vla) {
  1731. llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()];
  1732. assert(VlaSize && "no size for VLA!");
  1733. assert(VlaSize->getType() == SizeTy);
  1734. return { VlaSize, Vla->getElementType() };
  1735. }
  1736. void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
  1737. assert(type->isVariablyModifiedType() &&
  1738. "Must pass variably modified type to EmitVLASizes!");
  1739. EnsureInsertPoint();
  1740. // We're going to walk down into the type and look for VLA
  1741. // expressions.
  1742. do {
  1743. assert(type->isVariablyModifiedType());
  1744. const Type *ty = type.getTypePtr();
  1745. switch (ty->getTypeClass()) {
  1746. #define TYPE(Class, Base)
  1747. #define ABSTRACT_TYPE(Class, Base)
  1748. #define NON_CANONICAL_TYPE(Class, Base)
  1749. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  1750. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  1751. #include "clang/AST/TypeNodes.def"
  1752. llvm_unreachable("unexpected dependent type!");
  1753. // These types are never variably-modified.
  1754. case Type::Builtin:
  1755. case Type::Complex:
  1756. case Type::Vector:
  1757. case Type::ExtVector:
  1758. case Type::Record:
  1759. case Type::Enum:
  1760. case Type::Elaborated:
  1761. case Type::TemplateSpecialization:
  1762. case Type::ObjCTypeParam:
  1763. case Type::ObjCObject:
  1764. case Type::ObjCInterface:
  1765. case Type::ObjCObjectPointer:
  1766. llvm_unreachable("type class is never variably-modified!");
  1767. case Type::Adjusted:
  1768. type = cast<AdjustedType>(ty)->getAdjustedType();
  1769. break;
  1770. case Type::Decayed:
  1771. type = cast<DecayedType>(ty)->getPointeeType();
  1772. break;
  1773. case Type::Pointer:
  1774. type = cast<PointerType>(ty)->getPointeeType();
  1775. break;
  1776. case Type::BlockPointer:
  1777. type = cast<BlockPointerType>(ty)->getPointeeType();
  1778. break;
  1779. case Type::LValueReference:
  1780. case Type::RValueReference:
  1781. type = cast<ReferenceType>(ty)->getPointeeType();
  1782. break;
  1783. case Type::MemberPointer:
  1784. type = cast<MemberPointerType>(ty)->getPointeeType();
  1785. break;
  1786. case Type::ConstantArray:
  1787. case Type::IncompleteArray:
  1788. // Losing element qualification here is fine.
  1789. type = cast<ArrayType>(ty)->getElementType();
  1790. break;
  1791. case Type::VariableArray: {
  1792. // Losing element qualification here is fine.
  1793. const VariableArrayType *vat = cast<VariableArrayType>(ty);
  1794. // Unknown size indication requires no size computation.
  1795. // Otherwise, evaluate and record it.
  1796. if (const Expr *size = vat->getSizeExpr()) {
  1797. // It's possible that we might have emitted this already,
  1798. // e.g. with a typedef and a pointer to it.
  1799. llvm::Value *&entry = VLASizeMap[size];
  1800. if (!entry) {
  1801. llvm::Value *Size = EmitScalarExpr(size);
  1802. // C11 6.7.6.2p5:
  1803. // If the size is an expression that is not an integer constant
  1804. // expression [...] each time it is evaluated it shall have a value
  1805. // greater than zero.
  1806. if (SanOpts.has(SanitizerKind::VLABound) &&
  1807. size->getType()->isSignedIntegerType()) {
  1808. SanitizerScope SanScope(this);
  1809. llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
  1810. llvm::Constant *StaticArgs[] = {
  1811. EmitCheckSourceLocation(size->getBeginLoc()),
  1812. EmitCheckTypeDescriptor(size->getType())};
  1813. EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero),
  1814. SanitizerKind::VLABound),
  1815. SanitizerHandler::VLABoundNotPositive, StaticArgs, Size);
  1816. }
  1817. // Always zexting here would be wrong if it weren't
  1818. // undefined behavior to have a negative bound.
  1819. entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
  1820. }
  1821. }
  1822. type = vat->getElementType();
  1823. break;
  1824. }
  1825. case Type::FunctionProto:
  1826. case Type::FunctionNoProto:
  1827. type = cast<FunctionType>(ty)->getReturnType();
  1828. break;
  1829. case Type::Paren:
  1830. case Type::TypeOf:
  1831. case Type::UnaryTransform:
  1832. case Type::Attributed:
  1833. case Type::SubstTemplateTypeParm:
  1834. case Type::PackExpansion:
  1835. // Keep walking after single level desugaring.
  1836. type = type.getSingleStepDesugaredType(getContext());
  1837. break;
  1838. case Type::Typedef:
  1839. case Type::Decltype:
  1840. case Type::Auto:
  1841. case Type::DeducedTemplateSpecialization:
  1842. // Stop walking: nothing to do.
  1843. return;
  1844. case Type::TypeOfExpr:
  1845. // Stop walking: emit typeof expression.
  1846. EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
  1847. return;
  1848. case Type::Atomic:
  1849. type = cast<AtomicType>(ty)->getValueType();
  1850. break;
  1851. case Type::Pipe:
  1852. type = cast<PipeType>(ty)->getElementType();
  1853. break;
  1854. }
  1855. } while (type->isVariablyModifiedType());
  1856. }
  1857. Address CodeGenFunction::EmitVAListRef(const Expr* E) {
  1858. if (getContext().getBuiltinVaListType()->isArrayType())
  1859. return EmitPointerWithAlignment(E);
  1860. return EmitLValue(E).getAddress();
  1861. }
  1862. Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
  1863. return EmitLValue(E).getAddress();
  1864. }
  1865. void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
  1866. const APValue &Init) {
  1867. assert(!Init.isUninit() && "Invalid DeclRefExpr initializer!");
  1868. if (CGDebugInfo *Dbg = getDebugInfo())
  1869. if (CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
  1870. Dbg->EmitGlobalVariable(E->getDecl(), Init);
  1871. }
  1872. CodeGenFunction::PeepholeProtection
  1873. CodeGenFunction::protectFromPeepholes(RValue rvalue) {
  1874. // At the moment, the only aggressive peephole we do in IR gen
  1875. // is trunc(zext) folding, but if we add more, we can easily
  1876. // extend this protection.
  1877. if (!rvalue.isScalar()) return PeepholeProtection();
  1878. llvm::Value *value = rvalue.getScalarVal();
  1879. if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
  1880. // Just make an extra bitcast.
  1881. assert(HaveInsertPoint());
  1882. llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
  1883. Builder.GetInsertBlock());
  1884. PeepholeProtection protection;
  1885. protection.Inst = inst;
  1886. return protection;
  1887. }
  1888. void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
  1889. if (!protection.Inst) return;
  1890. // In theory, we could try to duplicate the peepholes now, but whatever.
  1891. protection.Inst->eraseFromParent();
  1892. }
  1893. llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
  1894. llvm::Value *AnnotatedVal,
  1895. StringRef AnnotationStr,
  1896. SourceLocation Location) {
  1897. llvm::Value *Args[4] = {
  1898. AnnotatedVal,
  1899. Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
  1900. Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
  1901. CGM.EmitAnnotationLineNo(Location)
  1902. };
  1903. return Builder.CreateCall(AnnotationFn, Args);
  1904. }
  1905. void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
  1906. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1907. // FIXME We create a new bitcast for every annotation because that's what
  1908. // llvm-gcc was doing.
  1909. for (const auto *I : D->specific_attrs<AnnotateAttr>())
  1910. EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
  1911. Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
  1912. I->getAnnotation(), D->getLocation());
  1913. }
  1914. Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
  1915. Address Addr) {
  1916. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1917. llvm::Value *V = Addr.getPointer();
  1918. llvm::Type *VTy = V->getType();
  1919. llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
  1920. CGM.Int8PtrTy);
  1921. for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
  1922. // FIXME Always emit the cast inst so we can differentiate between
  1923. // annotation on the first field of a struct and annotation on the struct
  1924. // itself.
  1925. if (VTy != CGM.Int8PtrTy)
  1926. V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
  1927. V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation());
  1928. V = Builder.CreateBitCast(V, VTy);
  1929. }
  1930. return Address(V, Addr.getAlignment());
  1931. }
  1932. CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
  1933. CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
  1934. : CGF(CGF) {
  1935. assert(!CGF->IsSanitizerScope);
  1936. CGF->IsSanitizerScope = true;
  1937. }
  1938. CodeGenFunction::SanitizerScope::~SanitizerScope() {
  1939. CGF->IsSanitizerScope = false;
  1940. }
  1941. void CodeGenFunction::InsertHelper(llvm::Instruction *I,
  1942. const llvm::Twine &Name,
  1943. llvm::BasicBlock *BB,
  1944. llvm::BasicBlock::iterator InsertPt) const {
  1945. LoopStack.InsertHelper(I);
  1946. if (IsSanitizerScope)
  1947. CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
  1948. }
  1949. void CGBuilderInserter::InsertHelper(
  1950. llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
  1951. llvm::BasicBlock::iterator InsertPt) const {
  1952. llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
  1953. if (CGF)
  1954. CGF->InsertHelper(I, Name, BB, InsertPt);
  1955. }
  1956. static bool hasRequiredFeatures(const SmallVectorImpl<StringRef> &ReqFeatures,
  1957. CodeGenModule &CGM, const FunctionDecl *FD,
  1958. std::string &FirstMissing) {
  1959. // If there aren't any required features listed then go ahead and return.
  1960. if (ReqFeatures.empty())
  1961. return false;
  1962. // Now build up the set of caller features and verify that all the required
  1963. // features are there.
  1964. llvm::StringMap<bool> CallerFeatureMap;
  1965. CGM.getFunctionFeatureMap(CallerFeatureMap, GlobalDecl().getWithDecl(FD));
  1966. // If we have at least one of the features in the feature list return
  1967. // true, otherwise return false.
  1968. return std::all_of(
  1969. ReqFeatures.begin(), ReqFeatures.end(), [&](StringRef Feature) {
  1970. SmallVector<StringRef, 1> OrFeatures;
  1971. Feature.split(OrFeatures, '|');
  1972. return llvm::any_of(OrFeatures, [&](StringRef Feature) {
  1973. if (!CallerFeatureMap.lookup(Feature)) {
  1974. FirstMissing = Feature.str();
  1975. return false;
  1976. }
  1977. return true;
  1978. });
  1979. });
  1980. }
  1981. // Emits an error if we don't have a valid set of target features for the
  1982. // called function.
  1983. void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
  1984. const FunctionDecl *TargetDecl) {
  1985. // Early exit if this is an indirect call.
  1986. if (!TargetDecl)
  1987. return;
  1988. // Get the current enclosing function if it exists. If it doesn't
  1989. // we can't check the target features anyhow.
  1990. const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl);
  1991. if (!FD)
  1992. return;
  1993. // Grab the required features for the call. For a builtin this is listed in
  1994. // the td file with the default cpu, for an always_inline function this is any
  1995. // listed cpu and any listed features.
  1996. unsigned BuiltinID = TargetDecl->getBuiltinID();
  1997. std::string MissingFeature;
  1998. if (BuiltinID) {
  1999. SmallVector<StringRef, 1> ReqFeatures;
  2000. const char *FeatureList =
  2001. CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
  2002. // Return if the builtin doesn't have any required features.
  2003. if (!FeatureList || StringRef(FeatureList) == "")
  2004. return;
  2005. StringRef(FeatureList).split(ReqFeatures, ',');
  2006. if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
  2007. CGM.getDiags().Report(E->getBeginLoc(), diag::err_builtin_needs_feature)
  2008. << TargetDecl->getDeclName()
  2009. << CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
  2010. } else if (TargetDecl->hasAttr<TargetAttr>() ||
  2011. TargetDecl->hasAttr<CPUSpecificAttr>()) {
  2012. // Get the required features for the callee.
  2013. const TargetAttr *TD = TargetDecl->getAttr<TargetAttr>();
  2014. TargetAttr::ParsedTargetAttr ParsedAttr = CGM.filterFunctionTargetAttrs(TD);
  2015. SmallVector<StringRef, 1> ReqFeatures;
  2016. llvm::StringMap<bool> CalleeFeatureMap;
  2017. CGM.getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
  2018. for (const auto &F : ParsedAttr.Features) {
  2019. if (F[0] == '+' && CalleeFeatureMap.lookup(F.substr(1)))
  2020. ReqFeatures.push_back(StringRef(F).substr(1));
  2021. }
  2022. for (const auto &F : CalleeFeatureMap) {
  2023. // Only positive features are "required".
  2024. if (F.getValue())
  2025. ReqFeatures.push_back(F.getKey());
  2026. }
  2027. if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
  2028. CGM.getDiags().Report(E->getBeginLoc(), diag::err_function_needs_feature)
  2029. << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
  2030. }
  2031. }
  2032. void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
  2033. if (!CGM.getCodeGenOpts().SanitizeStats)
  2034. return;
  2035. llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
  2036. IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
  2037. CGM.getSanStats().create(IRB, SSK);
  2038. }
  2039. llvm::Value *
  2040. CodeGenFunction::FormResolverCondition(const MultiVersionResolverOption &RO) {
  2041. llvm::Value *Condition = nullptr;
  2042. if (!RO.Conditions.Architecture.empty())
  2043. Condition = EmitX86CpuIs(RO.Conditions.Architecture);
  2044. if (!RO.Conditions.Features.empty()) {
  2045. llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Conditions.Features);
  2046. Condition =
  2047. Condition ? Builder.CreateAnd(Condition, FeatureCond) : FeatureCond;
  2048. }
  2049. return Condition;
  2050. }
  2051. static void CreateMultiVersionResolverReturn(CodeGenModule &CGM,
  2052. llvm::Function *Resolver,
  2053. CGBuilderTy &Builder,
  2054. llvm::Function *FuncToReturn,
  2055. bool SupportsIFunc) {
  2056. if (SupportsIFunc) {
  2057. Builder.CreateRet(FuncToReturn);
  2058. return;
  2059. }
  2060. llvm::SmallVector<llvm::Value *, 10> Args;
  2061. llvm::for_each(Resolver->args(),
  2062. [&](llvm::Argument &Arg) { Args.push_back(&Arg); });
  2063. llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args);
  2064. Result->setTailCallKind(llvm::CallInst::TCK_MustTail);
  2065. if (Resolver->getReturnType()->isVoidTy())
  2066. Builder.CreateRetVoid();
  2067. else
  2068. Builder.CreateRet(Result);
  2069. }
  2070. void CodeGenFunction::EmitMultiVersionResolver(
  2071. llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) {
  2072. assert((getContext().getTargetInfo().getTriple().getArch() ==
  2073. llvm::Triple::x86 ||
  2074. getContext().getTargetInfo().getTriple().getArch() ==
  2075. llvm::Triple::x86_64) &&
  2076. "Only implemented for x86 targets");
  2077. bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
  2078. // Main function's basic block.
  2079. llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
  2080. Builder.SetInsertPoint(CurBlock);
  2081. EmitX86CpuInit();
  2082. for (const MultiVersionResolverOption &RO : Options) {
  2083. Builder.SetInsertPoint(CurBlock);
  2084. llvm::Value *Condition = FormResolverCondition(RO);
  2085. // The 'default' or 'generic' case.
  2086. if (!Condition) {
  2087. assert(&RO == Options.end() - 1 &&
  2088. "Default or Generic case must be last");
  2089. CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
  2090. SupportsIFunc);
  2091. return;
  2092. }
  2093. llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
  2094. CGBuilderTy RetBuilder(*this, RetBlock);
  2095. CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
  2096. SupportsIFunc);
  2097. CurBlock = createBasicBlock("resolver_else", Resolver);
  2098. Builder.CreateCondBr(Condition, RetBlock, CurBlock);
  2099. }
  2100. // If no generic/default, emit an unreachable.
  2101. Builder.SetInsertPoint(CurBlock);
  2102. llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
  2103. TrapCall->setDoesNotReturn();
  2104. TrapCall->setDoesNotThrow();
  2105. Builder.CreateUnreachable();
  2106. Builder.ClearInsertionPoint();
  2107. }
  2108. llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) {
  2109. if (CGDebugInfo *DI = getDebugInfo())
  2110. return DI->SourceLocToDebugLoc(Location);
  2111. return llvm::DebugLoc();
  2112. }