CodeGenFunction.cpp 98 KB

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