CodeGenFunction.h 187 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394
  1. //===-- CodeGenFunction.h - Per-Function state for LLVM CodeGen -*- C++ -*-===//
  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 is the internal per-function state used for llvm translation.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
  13. #define LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
  14. #include "CGBuilder.h"
  15. #include "CGDebugInfo.h"
  16. #include "CGLoopInfo.h"
  17. #include "CGValue.h"
  18. #include "CodeGenModule.h"
  19. #include "CodeGenPGO.h"
  20. #include "EHScopeStack.h"
  21. #include "VarBypassDetector.h"
  22. #include "clang/AST/CharUnits.h"
  23. #include "clang/AST/CurrentSourceLocExprScope.h"
  24. #include "clang/AST/ExprCXX.h"
  25. #include "clang/AST/ExprObjC.h"
  26. #include "clang/AST/ExprOpenMP.h"
  27. #include "clang/AST/Type.h"
  28. #include "clang/Basic/ABI.h"
  29. #include "clang/Basic/CapturedStmt.h"
  30. #include "clang/Basic/CodeGenOptions.h"
  31. #include "clang/Basic/OpenMPKinds.h"
  32. #include "clang/Basic/TargetInfo.h"
  33. #include "llvm/ADT/ArrayRef.h"
  34. #include "llvm/ADT/DenseMap.h"
  35. #include "llvm/ADT/MapVector.h"
  36. #include "llvm/ADT/SmallVector.h"
  37. #include "llvm/IR/ValueHandle.h"
  38. #include "llvm/Support/Debug.h"
  39. #include "llvm/Transforms/Utils/SanitizerStats.h"
  40. namespace llvm {
  41. class BasicBlock;
  42. class LLVMContext;
  43. class MDNode;
  44. class Module;
  45. class SwitchInst;
  46. class Twine;
  47. class Value;
  48. }
  49. namespace clang {
  50. class ASTContext;
  51. class BlockDecl;
  52. class CXXDestructorDecl;
  53. class CXXForRangeStmt;
  54. class CXXTryStmt;
  55. class Decl;
  56. class LabelDecl;
  57. class EnumConstantDecl;
  58. class FunctionDecl;
  59. class FunctionProtoType;
  60. class LabelStmt;
  61. class ObjCContainerDecl;
  62. class ObjCInterfaceDecl;
  63. class ObjCIvarDecl;
  64. class ObjCMethodDecl;
  65. class ObjCImplementationDecl;
  66. class ObjCPropertyImplDecl;
  67. class TargetInfo;
  68. class VarDecl;
  69. class ObjCForCollectionStmt;
  70. class ObjCAtTryStmt;
  71. class ObjCAtThrowStmt;
  72. class ObjCAtSynchronizedStmt;
  73. class ObjCAutoreleasePoolStmt;
  74. namespace analyze_os_log {
  75. class OSLogBufferLayout;
  76. }
  77. namespace CodeGen {
  78. class CodeGenTypes;
  79. class CGCallee;
  80. class CGFunctionInfo;
  81. class CGRecordLayout;
  82. class CGBlockInfo;
  83. class CGCXXABI;
  84. class BlockByrefHelpers;
  85. class BlockByrefInfo;
  86. class BlockFlags;
  87. class BlockFieldFlags;
  88. class RegionCodeGenTy;
  89. class TargetCodeGenInfo;
  90. struct OMPTaskDataTy;
  91. struct CGCoroData;
  92. /// The kind of evaluation to perform on values of a particular
  93. /// type. Basically, is the code in CGExprScalar, CGExprComplex, or
  94. /// CGExprAgg?
  95. ///
  96. /// TODO: should vectors maybe be split out into their own thing?
  97. enum TypeEvaluationKind {
  98. TEK_Scalar,
  99. TEK_Complex,
  100. TEK_Aggregate
  101. };
  102. #define LIST_SANITIZER_CHECKS \
  103. SANITIZER_CHECK(AddOverflow, add_overflow, 0) \
  104. SANITIZER_CHECK(BuiltinUnreachable, builtin_unreachable, 0) \
  105. SANITIZER_CHECK(CFICheckFail, cfi_check_fail, 0) \
  106. SANITIZER_CHECK(DivremOverflow, divrem_overflow, 0) \
  107. SANITIZER_CHECK(DynamicTypeCacheMiss, dynamic_type_cache_miss, 0) \
  108. SANITIZER_CHECK(FloatCastOverflow, float_cast_overflow, 0) \
  109. SANITIZER_CHECK(FunctionTypeMismatch, function_type_mismatch, 1) \
  110. SANITIZER_CHECK(ImplicitConversion, implicit_conversion, 0) \
  111. SANITIZER_CHECK(InvalidBuiltin, invalid_builtin, 0) \
  112. SANITIZER_CHECK(LoadInvalidValue, load_invalid_value, 0) \
  113. SANITIZER_CHECK(MissingReturn, missing_return, 0) \
  114. SANITIZER_CHECK(MulOverflow, mul_overflow, 0) \
  115. SANITIZER_CHECK(NegateOverflow, negate_overflow, 0) \
  116. SANITIZER_CHECK(NullabilityArg, nullability_arg, 0) \
  117. SANITIZER_CHECK(NullabilityReturn, nullability_return, 1) \
  118. SANITIZER_CHECK(NonnullArg, nonnull_arg, 0) \
  119. SANITIZER_CHECK(NonnullReturn, nonnull_return, 1) \
  120. SANITIZER_CHECK(OutOfBounds, out_of_bounds, 0) \
  121. SANITIZER_CHECK(PointerOverflow, pointer_overflow, 0) \
  122. SANITIZER_CHECK(ShiftOutOfBounds, shift_out_of_bounds, 0) \
  123. SANITIZER_CHECK(SubOverflow, sub_overflow, 0) \
  124. SANITIZER_CHECK(TypeMismatch, type_mismatch, 1) \
  125. SANITIZER_CHECK(AlignmentAssumption, alignment_assumption, 0) \
  126. SANITIZER_CHECK(VLABoundNotPositive, vla_bound_not_positive, 0)
  127. enum SanitizerHandler {
  128. #define SANITIZER_CHECK(Enum, Name, Version) Enum,
  129. LIST_SANITIZER_CHECKS
  130. #undef SANITIZER_CHECK
  131. };
  132. /// Helper class with most of the code for saving a value for a
  133. /// conditional expression cleanup.
  134. struct DominatingLLVMValue {
  135. typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
  136. /// Answer whether the given value needs extra work to be saved.
  137. static bool needsSaving(llvm::Value *value) {
  138. // If it's not an instruction, we don't need to save.
  139. if (!isa<llvm::Instruction>(value)) return false;
  140. // If it's an instruction in the entry block, we don't need to save.
  141. llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
  142. return (block != &block->getParent()->getEntryBlock());
  143. }
  144. static saved_type save(CodeGenFunction &CGF, llvm::Value *value);
  145. static llvm::Value *restore(CodeGenFunction &CGF, saved_type value);
  146. };
  147. /// A partial specialization of DominatingValue for llvm::Values that
  148. /// might be llvm::Instructions.
  149. template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
  150. typedef T *type;
  151. static type restore(CodeGenFunction &CGF, saved_type value) {
  152. return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
  153. }
  154. };
  155. /// A specialization of DominatingValue for Address.
  156. template <> struct DominatingValue<Address> {
  157. typedef Address type;
  158. struct saved_type {
  159. DominatingLLVMValue::saved_type SavedValue;
  160. CharUnits Alignment;
  161. };
  162. static bool needsSaving(type value) {
  163. return DominatingLLVMValue::needsSaving(value.getPointer());
  164. }
  165. static saved_type save(CodeGenFunction &CGF, type value) {
  166. return { DominatingLLVMValue::save(CGF, value.getPointer()),
  167. value.getAlignment() };
  168. }
  169. static type restore(CodeGenFunction &CGF, saved_type value) {
  170. return Address(DominatingLLVMValue::restore(CGF, value.SavedValue),
  171. value.Alignment);
  172. }
  173. };
  174. /// A specialization of DominatingValue for RValue.
  175. template <> struct DominatingValue<RValue> {
  176. typedef RValue type;
  177. class saved_type {
  178. enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
  179. AggregateAddress, ComplexAddress };
  180. llvm::Value *Value;
  181. unsigned K : 3;
  182. unsigned Align : 29;
  183. saved_type(llvm::Value *v, Kind k, unsigned a = 0)
  184. : Value(v), K(k), Align(a) {}
  185. public:
  186. static bool needsSaving(RValue value);
  187. static saved_type save(CodeGenFunction &CGF, RValue value);
  188. RValue restore(CodeGenFunction &CGF);
  189. // implementations in CGCleanup.cpp
  190. };
  191. static bool needsSaving(type value) {
  192. return saved_type::needsSaving(value);
  193. }
  194. static saved_type save(CodeGenFunction &CGF, type value) {
  195. return saved_type::save(CGF, value);
  196. }
  197. static type restore(CodeGenFunction &CGF, saved_type value) {
  198. return value.restore(CGF);
  199. }
  200. };
  201. /// CodeGenFunction - This class organizes the per-function state that is used
  202. /// while generating LLVM code.
  203. class CodeGenFunction : public CodeGenTypeCache {
  204. CodeGenFunction(const CodeGenFunction &) = delete;
  205. void operator=(const CodeGenFunction &) = delete;
  206. friend class CGCXXABI;
  207. public:
  208. /// A jump destination is an abstract label, branching to which may
  209. /// require a jump out through normal cleanups.
  210. struct JumpDest {
  211. JumpDest() : Block(nullptr), ScopeDepth(), Index(0) {}
  212. JumpDest(llvm::BasicBlock *Block,
  213. EHScopeStack::stable_iterator Depth,
  214. unsigned Index)
  215. : Block(Block), ScopeDepth(Depth), Index(Index) {}
  216. bool isValid() const { return Block != nullptr; }
  217. llvm::BasicBlock *getBlock() const { return Block; }
  218. EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
  219. unsigned getDestIndex() const { return Index; }
  220. // This should be used cautiously.
  221. void setScopeDepth(EHScopeStack::stable_iterator depth) {
  222. ScopeDepth = depth;
  223. }
  224. private:
  225. llvm::BasicBlock *Block;
  226. EHScopeStack::stable_iterator ScopeDepth;
  227. unsigned Index;
  228. };
  229. CodeGenModule &CGM; // Per-module state.
  230. const TargetInfo &Target;
  231. typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
  232. LoopInfoStack LoopStack;
  233. CGBuilderTy Builder;
  234. // Stores variables for which we can't generate correct lifetime markers
  235. // because of jumps.
  236. VarBypassDetector Bypasses;
  237. // CodeGen lambda for loops and support for ordered clause
  238. typedef llvm::function_ref<void(CodeGenFunction &, const OMPLoopDirective &,
  239. JumpDest)>
  240. CodeGenLoopTy;
  241. typedef llvm::function_ref<void(CodeGenFunction &, SourceLocation,
  242. const unsigned, const bool)>
  243. CodeGenOrderedTy;
  244. // Codegen lambda for loop bounds in worksharing loop constructs
  245. typedef llvm::function_ref<std::pair<LValue, LValue>(
  246. CodeGenFunction &, const OMPExecutableDirective &S)>
  247. CodeGenLoopBoundsTy;
  248. // Codegen lambda for loop bounds in dispatch-based loop implementation
  249. typedef llvm::function_ref<std::pair<llvm::Value *, llvm::Value *>(
  250. CodeGenFunction &, const OMPExecutableDirective &S, Address LB,
  251. Address UB)>
  252. CodeGenDispatchBoundsTy;
  253. /// CGBuilder insert helper. This function is called after an
  254. /// instruction is created using Builder.
  255. void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name,
  256. llvm::BasicBlock *BB,
  257. llvm::BasicBlock::iterator InsertPt) const;
  258. /// CurFuncDecl - Holds the Decl for the current outermost
  259. /// non-closure context.
  260. const Decl *CurFuncDecl;
  261. /// CurCodeDecl - This is the inner-most code context, which includes blocks.
  262. const Decl *CurCodeDecl;
  263. const CGFunctionInfo *CurFnInfo;
  264. QualType FnRetTy;
  265. llvm::Function *CurFn = nullptr;
  266. // Holds coroutine data if the current function is a coroutine. We use a
  267. // wrapper to manage its lifetime, so that we don't have to define CGCoroData
  268. // in this header.
  269. struct CGCoroInfo {
  270. std::unique_ptr<CGCoroData> Data;
  271. CGCoroInfo();
  272. ~CGCoroInfo();
  273. };
  274. CGCoroInfo CurCoro;
  275. bool isCoroutine() const {
  276. return CurCoro.Data != nullptr;
  277. }
  278. /// CurGD - The GlobalDecl for the current function being compiled.
  279. GlobalDecl CurGD;
  280. /// PrologueCleanupDepth - The cleanup depth enclosing all the
  281. /// cleanups associated with the parameters.
  282. EHScopeStack::stable_iterator PrologueCleanupDepth;
  283. /// ReturnBlock - Unified return block.
  284. JumpDest ReturnBlock;
  285. /// ReturnValue - The temporary alloca to hold the return
  286. /// value. This is invalid iff the function has no return value.
  287. Address ReturnValue = Address::invalid();
  288. /// ReturnValuePointer - The temporary alloca to hold a pointer to sret.
  289. /// This is invalid if sret is not in use.
  290. Address ReturnValuePointer = Address::invalid();
  291. /// Return true if a label was seen in the current scope.
  292. bool hasLabelBeenSeenInCurrentScope() const {
  293. if (CurLexicalScope)
  294. return CurLexicalScope->hasLabels();
  295. return !LabelMap.empty();
  296. }
  297. /// AllocaInsertPoint - This is an instruction in the entry block before which
  298. /// we prefer to insert allocas.
  299. llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
  300. /// API for captured statement code generation.
  301. class CGCapturedStmtInfo {
  302. public:
  303. explicit CGCapturedStmtInfo(CapturedRegionKind K = CR_Default)
  304. : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {}
  305. explicit CGCapturedStmtInfo(const CapturedStmt &S,
  306. CapturedRegionKind K = CR_Default)
  307. : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {
  308. RecordDecl::field_iterator Field =
  309. S.getCapturedRecordDecl()->field_begin();
  310. for (CapturedStmt::const_capture_iterator I = S.capture_begin(),
  311. E = S.capture_end();
  312. I != E; ++I, ++Field) {
  313. if (I->capturesThis())
  314. CXXThisFieldDecl = *Field;
  315. else if (I->capturesVariable())
  316. CaptureFields[I->getCapturedVar()->getCanonicalDecl()] = *Field;
  317. else if (I->capturesVariableByCopy())
  318. CaptureFields[I->getCapturedVar()->getCanonicalDecl()] = *Field;
  319. }
  320. }
  321. virtual ~CGCapturedStmtInfo();
  322. CapturedRegionKind getKind() const { return Kind; }
  323. virtual void setContextValue(llvm::Value *V) { ThisValue = V; }
  324. // Retrieve the value of the context parameter.
  325. virtual llvm::Value *getContextValue() const { return ThisValue; }
  326. /// Lookup the captured field decl for a variable.
  327. virtual const FieldDecl *lookup(const VarDecl *VD) const {
  328. return CaptureFields.lookup(VD->getCanonicalDecl());
  329. }
  330. bool isCXXThisExprCaptured() const { return getThisFieldDecl() != nullptr; }
  331. virtual FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; }
  332. static bool classof(const CGCapturedStmtInfo *) {
  333. return true;
  334. }
  335. /// Emit the captured statement body.
  336. virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) {
  337. CGF.incrementProfileCounter(S);
  338. CGF.EmitStmt(S);
  339. }
  340. /// Get the name of the capture helper.
  341. virtual StringRef getHelperName() const { return "__captured_stmt"; }
  342. private:
  343. /// The kind of captured statement being generated.
  344. CapturedRegionKind Kind;
  345. /// Keep the map between VarDecl and FieldDecl.
  346. llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields;
  347. /// The base address of the captured record, passed in as the first
  348. /// argument of the parallel region function.
  349. llvm::Value *ThisValue;
  350. /// Captured 'this' type.
  351. FieldDecl *CXXThisFieldDecl;
  352. };
  353. CGCapturedStmtInfo *CapturedStmtInfo = nullptr;
  354. /// RAII for correct setting/restoring of CapturedStmtInfo.
  355. class CGCapturedStmtRAII {
  356. private:
  357. CodeGenFunction &CGF;
  358. CGCapturedStmtInfo *PrevCapturedStmtInfo;
  359. public:
  360. CGCapturedStmtRAII(CodeGenFunction &CGF,
  361. CGCapturedStmtInfo *NewCapturedStmtInfo)
  362. : CGF(CGF), PrevCapturedStmtInfo(CGF.CapturedStmtInfo) {
  363. CGF.CapturedStmtInfo = NewCapturedStmtInfo;
  364. }
  365. ~CGCapturedStmtRAII() { CGF.CapturedStmtInfo = PrevCapturedStmtInfo; }
  366. };
  367. /// An abstract representation of regular/ObjC call/message targets.
  368. class AbstractCallee {
  369. /// The function declaration of the callee.
  370. const Decl *CalleeDecl;
  371. public:
  372. AbstractCallee() : CalleeDecl(nullptr) {}
  373. AbstractCallee(const FunctionDecl *FD) : CalleeDecl(FD) {}
  374. AbstractCallee(const ObjCMethodDecl *OMD) : CalleeDecl(OMD) {}
  375. bool hasFunctionDecl() const {
  376. return dyn_cast_or_null<FunctionDecl>(CalleeDecl);
  377. }
  378. const Decl *getDecl() const { return CalleeDecl; }
  379. unsigned getNumParams() const {
  380. if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
  381. return FD->getNumParams();
  382. return cast<ObjCMethodDecl>(CalleeDecl)->param_size();
  383. }
  384. const ParmVarDecl *getParamDecl(unsigned I) const {
  385. if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
  386. return FD->getParamDecl(I);
  387. return *(cast<ObjCMethodDecl>(CalleeDecl)->param_begin() + I);
  388. }
  389. };
  390. /// Sanitizers enabled for this function.
  391. SanitizerSet SanOpts;
  392. /// True if CodeGen currently emits code implementing sanitizer checks.
  393. bool IsSanitizerScope = false;
  394. /// RAII object to set/unset CodeGenFunction::IsSanitizerScope.
  395. class SanitizerScope {
  396. CodeGenFunction *CGF;
  397. public:
  398. SanitizerScope(CodeGenFunction *CGF);
  399. ~SanitizerScope();
  400. };
  401. /// In C++, whether we are code generating a thunk. This controls whether we
  402. /// should emit cleanups.
  403. bool CurFuncIsThunk = false;
  404. /// In ARC, whether we should autorelease the return value.
  405. bool AutoreleaseResult = false;
  406. /// Whether we processed a Microsoft-style asm block during CodeGen. These can
  407. /// potentially set the return value.
  408. bool SawAsmBlock = false;
  409. const NamedDecl *CurSEHParent = nullptr;
  410. /// True if the current function is an outlined SEH helper. This can be a
  411. /// finally block or filter expression.
  412. bool IsOutlinedSEHHelper = false;
  413. /// True if CodeGen currently emits code inside presereved access index
  414. /// region.
  415. bool IsInPreservedAIRegion = false;
  416. const CodeGen::CGBlockInfo *BlockInfo = nullptr;
  417. llvm::Value *BlockPointer = nullptr;
  418. llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
  419. FieldDecl *LambdaThisCaptureField = nullptr;
  420. /// A mapping from NRVO variables to the flags used to indicate
  421. /// when the NRVO has been applied to this variable.
  422. llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
  423. EHScopeStack EHStack;
  424. llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack;
  425. llvm::SmallVector<const JumpDest *, 2> SEHTryEpilogueStack;
  426. llvm::Instruction *CurrentFuncletPad = nullptr;
  427. class CallLifetimeEnd final : public EHScopeStack::Cleanup {
  428. llvm::Value *Addr;
  429. llvm::Value *Size;
  430. public:
  431. CallLifetimeEnd(Address addr, llvm::Value *size)
  432. : Addr(addr.getPointer()), Size(size) {}
  433. void Emit(CodeGenFunction &CGF, Flags flags) override {
  434. CGF.EmitLifetimeEnd(Size, Addr);
  435. }
  436. };
  437. /// Header for data within LifetimeExtendedCleanupStack.
  438. struct LifetimeExtendedCleanupHeader {
  439. /// The size of the following cleanup object.
  440. unsigned Size;
  441. /// The kind of cleanup to push: a value from the CleanupKind enumeration.
  442. unsigned Kind : 31;
  443. /// Whether this is a conditional cleanup.
  444. unsigned IsConditional : 1;
  445. size_t getSize() const { return Size; }
  446. CleanupKind getKind() const { return (CleanupKind)Kind; }
  447. bool isConditional() const { return IsConditional; }
  448. };
  449. /// i32s containing the indexes of the cleanup destinations.
  450. Address NormalCleanupDest = Address::invalid();
  451. unsigned NextCleanupDestIndex = 1;
  452. /// FirstBlockInfo - The head of a singly-linked-list of block layouts.
  453. CGBlockInfo *FirstBlockInfo = nullptr;
  454. /// EHResumeBlock - Unified block containing a call to llvm.eh.resume.
  455. llvm::BasicBlock *EHResumeBlock = nullptr;
  456. /// The exception slot. All landing pads write the current exception pointer
  457. /// into this alloca.
  458. llvm::Value *ExceptionSlot = nullptr;
  459. /// The selector slot. Under the MandatoryCleanup model, all landing pads
  460. /// write the current selector value into this alloca.
  461. llvm::AllocaInst *EHSelectorSlot = nullptr;
  462. /// A stack of exception code slots. Entering an __except block pushes a slot
  463. /// on the stack and leaving pops one. The __exception_code() intrinsic loads
  464. /// a value from the top of the stack.
  465. SmallVector<Address, 1> SEHCodeSlotStack;
  466. /// Value returned by __exception_info intrinsic.
  467. llvm::Value *SEHInfo = nullptr;
  468. /// Emits a landing pad for the current EH stack.
  469. llvm::BasicBlock *EmitLandingPad();
  470. llvm::BasicBlock *getInvokeDestImpl();
  471. template <class T>
  472. typename DominatingValue<T>::saved_type saveValueInCond(T value) {
  473. return DominatingValue<T>::save(*this, value);
  474. }
  475. public:
  476. /// ObjCEHValueStack - Stack of Objective-C exception values, used for
  477. /// rethrows.
  478. SmallVector<llvm::Value*, 8> ObjCEHValueStack;
  479. /// A class controlling the emission of a finally block.
  480. class FinallyInfo {
  481. /// Where the catchall's edge through the cleanup should go.
  482. JumpDest RethrowDest;
  483. /// A function to call to enter the catch.
  484. llvm::FunctionCallee BeginCatchFn;
  485. /// An i1 variable indicating whether or not the @finally is
  486. /// running for an exception.
  487. llvm::AllocaInst *ForEHVar;
  488. /// An i8* variable into which the exception pointer to rethrow
  489. /// has been saved.
  490. llvm::AllocaInst *SavedExnVar;
  491. public:
  492. void enter(CodeGenFunction &CGF, const Stmt *Finally,
  493. llvm::FunctionCallee beginCatchFn,
  494. llvm::FunctionCallee endCatchFn, llvm::FunctionCallee rethrowFn);
  495. void exit(CodeGenFunction &CGF);
  496. };
  497. /// Returns true inside SEH __try blocks.
  498. bool isSEHTryScope() const { return !SEHTryEpilogueStack.empty(); }
  499. /// Returns true while emitting a cleanuppad.
  500. bool isCleanupPadScope() const {
  501. return CurrentFuncletPad && isa<llvm::CleanupPadInst>(CurrentFuncletPad);
  502. }
  503. /// pushFullExprCleanup - Push a cleanup to be run at the end of the
  504. /// current full-expression. Safe against the possibility that
  505. /// we're currently inside a conditionally-evaluated expression.
  506. template <class T, class... As>
  507. void pushFullExprCleanup(CleanupKind kind, As... A) {
  508. // If we're not in a conditional branch, or if none of the
  509. // arguments requires saving, then use the unconditional cleanup.
  510. if (!isInConditionalBranch())
  511. return EHStack.pushCleanup<T>(kind, A...);
  512. // Stash values in a tuple so we can guarantee the order of saves.
  513. typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
  514. SavedTuple Saved{saveValueInCond(A)...};
  515. typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
  516. EHStack.pushCleanupTuple<CleanupType>(kind, Saved);
  517. initFullExprCleanup();
  518. }
  519. /// Queue a cleanup to be pushed after finishing the current
  520. /// full-expression.
  521. template <class T, class... As>
  522. void pushCleanupAfterFullExpr(CleanupKind Kind, As... A) {
  523. if (!isInConditionalBranch())
  524. return pushCleanupAfterFullExprImpl<T>(Kind, Address::invalid(), A...);
  525. Address ActiveFlag = createCleanupActiveFlag();
  526. assert(!DominatingValue<Address>::needsSaving(ActiveFlag) &&
  527. "cleanup active flag should never need saving");
  528. typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
  529. SavedTuple Saved{saveValueInCond(A)...};
  530. typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
  531. pushCleanupAfterFullExprImpl<CleanupType>(Kind, ActiveFlag, Saved);
  532. }
  533. template <class T, class... As>
  534. void pushCleanupAfterFullExprImpl(CleanupKind Kind, Address ActiveFlag,
  535. As... A) {
  536. LifetimeExtendedCleanupHeader Header = {sizeof(T), Kind,
  537. ActiveFlag.isValid()};
  538. size_t OldSize = LifetimeExtendedCleanupStack.size();
  539. LifetimeExtendedCleanupStack.resize(
  540. LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size +
  541. (Header.IsConditional ? sizeof(ActiveFlag) : 0));
  542. static_assert(sizeof(Header) % alignof(T) == 0,
  543. "Cleanup will be allocated on misaligned address");
  544. char *Buffer = &LifetimeExtendedCleanupStack[OldSize];
  545. new (Buffer) LifetimeExtendedCleanupHeader(Header);
  546. new (Buffer + sizeof(Header)) T(A...);
  547. if (Header.IsConditional)
  548. new (Buffer + sizeof(Header) + sizeof(T)) Address(ActiveFlag);
  549. }
  550. /// Set up the last cleanup that was pushed as a conditional
  551. /// full-expression cleanup.
  552. void initFullExprCleanup() {
  553. initFullExprCleanupWithFlag(createCleanupActiveFlag());
  554. }
  555. void initFullExprCleanupWithFlag(Address ActiveFlag);
  556. Address createCleanupActiveFlag();
  557. /// PushDestructorCleanup - Push a cleanup to call the
  558. /// complete-object destructor of an object of the given type at the
  559. /// given address. Does nothing if T is not a C++ class type with a
  560. /// non-trivial destructor.
  561. void PushDestructorCleanup(QualType T, Address Addr);
  562. /// PushDestructorCleanup - Push a cleanup to call the
  563. /// complete-object variant of the given destructor on the object at
  564. /// the given address.
  565. void PushDestructorCleanup(const CXXDestructorDecl *Dtor, QualType T,
  566. Address Addr);
  567. /// PopCleanupBlock - Will pop the cleanup entry on the stack and
  568. /// process all branch fixups.
  569. void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
  570. /// DeactivateCleanupBlock - Deactivates the given cleanup block.
  571. /// The block cannot be reactivated. Pops it if it's the top of the
  572. /// stack.
  573. ///
  574. /// \param DominatingIP - An instruction which is known to
  575. /// dominate the current IP (if set) and which lies along
  576. /// all paths of execution between the current IP and the
  577. /// the point at which the cleanup comes into scope.
  578. void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
  579. llvm::Instruction *DominatingIP);
  580. /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
  581. /// Cannot be used to resurrect a deactivated cleanup.
  582. ///
  583. /// \param DominatingIP - An instruction which is known to
  584. /// dominate the current IP (if set) and which lies along
  585. /// all paths of execution between the current IP and the
  586. /// the point at which the cleanup comes into scope.
  587. void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
  588. llvm::Instruction *DominatingIP);
  589. /// Enters a new scope for capturing cleanups, all of which
  590. /// will be executed once the scope is exited.
  591. class RunCleanupsScope {
  592. EHScopeStack::stable_iterator CleanupStackDepth, OldCleanupScopeDepth;
  593. size_t LifetimeExtendedCleanupStackSize;
  594. bool OldDidCallStackSave;
  595. protected:
  596. bool PerformCleanup;
  597. private:
  598. RunCleanupsScope(const RunCleanupsScope &) = delete;
  599. void operator=(const RunCleanupsScope &) = delete;
  600. protected:
  601. CodeGenFunction& CGF;
  602. public:
  603. /// Enter a new cleanup scope.
  604. explicit RunCleanupsScope(CodeGenFunction &CGF)
  605. : PerformCleanup(true), CGF(CGF)
  606. {
  607. CleanupStackDepth = CGF.EHStack.stable_begin();
  608. LifetimeExtendedCleanupStackSize =
  609. CGF.LifetimeExtendedCleanupStack.size();
  610. OldDidCallStackSave = CGF.DidCallStackSave;
  611. CGF.DidCallStackSave = false;
  612. OldCleanupScopeDepth = CGF.CurrentCleanupScopeDepth;
  613. CGF.CurrentCleanupScopeDepth = CleanupStackDepth;
  614. }
  615. /// Exit this cleanup scope, emitting any accumulated cleanups.
  616. ~RunCleanupsScope() {
  617. if (PerformCleanup)
  618. ForceCleanup();
  619. }
  620. /// Determine whether this scope requires any cleanups.
  621. bool requiresCleanups() const {
  622. return CGF.EHStack.stable_begin() != CleanupStackDepth;
  623. }
  624. /// Force the emission of cleanups now, instead of waiting
  625. /// until this object is destroyed.
  626. /// \param ValuesToReload - A list of values that need to be available at
  627. /// the insertion point after cleanup emission. If cleanup emission created
  628. /// a shared cleanup block, these value pointers will be rewritten.
  629. /// Otherwise, they not will be modified.
  630. void ForceCleanup(std::initializer_list<llvm::Value**> ValuesToReload = {}) {
  631. assert(PerformCleanup && "Already forced cleanup");
  632. CGF.DidCallStackSave = OldDidCallStackSave;
  633. CGF.PopCleanupBlocks(CleanupStackDepth, LifetimeExtendedCleanupStackSize,
  634. ValuesToReload);
  635. PerformCleanup = false;
  636. CGF.CurrentCleanupScopeDepth = OldCleanupScopeDepth;
  637. }
  638. };
  639. // Cleanup stack depth of the RunCleanupsScope that was pushed most recently.
  640. EHScopeStack::stable_iterator CurrentCleanupScopeDepth =
  641. EHScopeStack::stable_end();
  642. class LexicalScope : public RunCleanupsScope {
  643. SourceRange Range;
  644. SmallVector<const LabelDecl*, 4> Labels;
  645. LexicalScope *ParentScope;
  646. LexicalScope(const LexicalScope &) = delete;
  647. void operator=(const LexicalScope &) = delete;
  648. public:
  649. /// Enter a new cleanup scope.
  650. explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range)
  651. : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) {
  652. CGF.CurLexicalScope = this;
  653. if (CGDebugInfo *DI = CGF.getDebugInfo())
  654. DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin());
  655. }
  656. void addLabel(const LabelDecl *label) {
  657. assert(PerformCleanup && "adding label to dead scope?");
  658. Labels.push_back(label);
  659. }
  660. /// Exit this cleanup scope, emitting any accumulated
  661. /// cleanups.
  662. ~LexicalScope() {
  663. if (CGDebugInfo *DI = CGF.getDebugInfo())
  664. DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
  665. // If we should perform a cleanup, force them now. Note that
  666. // this ends the cleanup scope before rescoping any labels.
  667. if (PerformCleanup) {
  668. ApplyDebugLocation DL(CGF, Range.getEnd());
  669. ForceCleanup();
  670. }
  671. }
  672. /// Force the emission of cleanups now, instead of waiting
  673. /// until this object is destroyed.
  674. void ForceCleanup() {
  675. CGF.CurLexicalScope = ParentScope;
  676. RunCleanupsScope::ForceCleanup();
  677. if (!Labels.empty())
  678. rescopeLabels();
  679. }
  680. bool hasLabels() const {
  681. return !Labels.empty();
  682. }
  683. void rescopeLabels();
  684. };
  685. typedef llvm::DenseMap<const Decl *, Address> DeclMapTy;
  686. /// The class used to assign some variables some temporarily addresses.
  687. class OMPMapVars {
  688. DeclMapTy SavedLocals;
  689. DeclMapTy SavedTempAddresses;
  690. OMPMapVars(const OMPMapVars &) = delete;
  691. void operator=(const OMPMapVars &) = delete;
  692. public:
  693. explicit OMPMapVars() = default;
  694. ~OMPMapVars() {
  695. assert(SavedLocals.empty() && "Did not restored original addresses.");
  696. };
  697. /// Sets the address of the variable \p LocalVD to be \p TempAddr in
  698. /// function \p CGF.
  699. /// \return true if at least one variable was set already, false otherwise.
  700. bool setVarAddr(CodeGenFunction &CGF, const VarDecl *LocalVD,
  701. Address TempAddr) {
  702. LocalVD = LocalVD->getCanonicalDecl();
  703. // Only save it once.
  704. if (SavedLocals.count(LocalVD)) return false;
  705. // Copy the existing local entry to SavedLocals.
  706. auto it = CGF.LocalDeclMap.find(LocalVD);
  707. if (it != CGF.LocalDeclMap.end())
  708. SavedLocals.try_emplace(LocalVD, it->second);
  709. else
  710. SavedLocals.try_emplace(LocalVD, Address::invalid());
  711. // Generate the private entry.
  712. QualType VarTy = LocalVD->getType();
  713. if (VarTy->isReferenceType()) {
  714. Address Temp = CGF.CreateMemTemp(VarTy);
  715. CGF.Builder.CreateStore(TempAddr.getPointer(), Temp);
  716. TempAddr = Temp;
  717. }
  718. SavedTempAddresses.try_emplace(LocalVD, TempAddr);
  719. return true;
  720. }
  721. /// Applies new addresses to the list of the variables.
  722. /// \return true if at least one variable is using new address, false
  723. /// otherwise.
  724. bool apply(CodeGenFunction &CGF) {
  725. copyInto(SavedTempAddresses, CGF.LocalDeclMap);
  726. SavedTempAddresses.clear();
  727. return !SavedLocals.empty();
  728. }
  729. /// Restores original addresses of the variables.
  730. void restore(CodeGenFunction &CGF) {
  731. if (!SavedLocals.empty()) {
  732. copyInto(SavedLocals, CGF.LocalDeclMap);
  733. SavedLocals.clear();
  734. }
  735. }
  736. private:
  737. /// Copy all the entries in the source map over the corresponding
  738. /// entries in the destination, which must exist.
  739. static void copyInto(const DeclMapTy &Src, DeclMapTy &Dest) {
  740. for (auto &Pair : Src) {
  741. if (!Pair.second.isValid()) {
  742. Dest.erase(Pair.first);
  743. continue;
  744. }
  745. auto I = Dest.find(Pair.first);
  746. if (I != Dest.end())
  747. I->second = Pair.second;
  748. else
  749. Dest.insert(Pair);
  750. }
  751. }
  752. };
  753. /// The scope used to remap some variables as private in the OpenMP loop body
  754. /// (or other captured region emitted without outlining), and to restore old
  755. /// vars back on exit.
  756. class OMPPrivateScope : public RunCleanupsScope {
  757. OMPMapVars MappedVars;
  758. OMPPrivateScope(const OMPPrivateScope &) = delete;
  759. void operator=(const OMPPrivateScope &) = delete;
  760. public:
  761. /// Enter a new OpenMP private scope.
  762. explicit OMPPrivateScope(CodeGenFunction &CGF) : RunCleanupsScope(CGF) {}
  763. /// Registers \p LocalVD variable as a private and apply \p PrivateGen
  764. /// function for it to generate corresponding private variable. \p
  765. /// PrivateGen returns an address of the generated private variable.
  766. /// \return true if the variable is registered as private, false if it has
  767. /// been privatized already.
  768. bool addPrivate(const VarDecl *LocalVD,
  769. const llvm::function_ref<Address()> PrivateGen) {
  770. assert(PerformCleanup && "adding private to dead scope");
  771. return MappedVars.setVarAddr(CGF, LocalVD, PrivateGen());
  772. }
  773. /// Privatizes local variables previously registered as private.
  774. /// Registration is separate from the actual privatization to allow
  775. /// initializers use values of the original variables, not the private one.
  776. /// This is important, for example, if the private variable is a class
  777. /// variable initialized by a constructor that references other private
  778. /// variables. But at initialization original variables must be used, not
  779. /// private copies.
  780. /// \return true if at least one variable was privatized, false otherwise.
  781. bool Privatize() { return MappedVars.apply(CGF); }
  782. void ForceCleanup() {
  783. RunCleanupsScope::ForceCleanup();
  784. MappedVars.restore(CGF);
  785. }
  786. /// Exit scope - all the mapped variables are restored.
  787. ~OMPPrivateScope() {
  788. if (PerformCleanup)
  789. ForceCleanup();
  790. }
  791. /// Checks if the global variable is captured in current function.
  792. bool isGlobalVarCaptured(const VarDecl *VD) const {
  793. VD = VD->getCanonicalDecl();
  794. return !VD->isLocalVarDeclOrParm() && CGF.LocalDeclMap.count(VD) > 0;
  795. }
  796. };
  797. /// Takes the old cleanup stack size and emits the cleanup blocks
  798. /// that have been added.
  799. void
  800. PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
  801. std::initializer_list<llvm::Value **> ValuesToReload = {});
  802. /// Takes the old cleanup stack size and emits the cleanup blocks
  803. /// that have been added, then adds all lifetime-extended cleanups from
  804. /// the given position to the stack.
  805. void
  806. PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
  807. size_t OldLifetimeExtendedStackSize,
  808. std::initializer_list<llvm::Value **> ValuesToReload = {});
  809. void ResolveBranchFixups(llvm::BasicBlock *Target);
  810. /// The given basic block lies in the current EH scope, but may be a
  811. /// target of a potentially scope-crossing jump; get a stable handle
  812. /// to which we can perform this jump later.
  813. JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
  814. return JumpDest(Target,
  815. EHStack.getInnermostNormalCleanup(),
  816. NextCleanupDestIndex++);
  817. }
  818. /// The given basic block lies in the current EH scope, but may be a
  819. /// target of a potentially scope-crossing jump; get a stable handle
  820. /// to which we can perform this jump later.
  821. JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) {
  822. return getJumpDestInCurrentScope(createBasicBlock(Name));
  823. }
  824. /// EmitBranchThroughCleanup - Emit a branch from the current insert
  825. /// block through the normal cleanup handling code (if any) and then
  826. /// on to \arg Dest.
  827. void EmitBranchThroughCleanup(JumpDest Dest);
  828. /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
  829. /// specified destination obviously has no cleanups to run. 'false' is always
  830. /// a conservatively correct answer for this method.
  831. bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const;
  832. /// popCatchScope - Pops the catch scope at the top of the EHScope
  833. /// stack, emitting any required code (other than the catch handlers
  834. /// themselves).
  835. void popCatchScope();
  836. llvm::BasicBlock *getEHResumeBlock(bool isCleanup);
  837. llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope);
  838. llvm::BasicBlock *
  839. getFuncletEHDispatchBlock(EHScopeStack::stable_iterator scope);
  840. /// An object to manage conditionally-evaluated expressions.
  841. class ConditionalEvaluation {
  842. llvm::BasicBlock *StartBB;
  843. public:
  844. ConditionalEvaluation(CodeGenFunction &CGF)
  845. : StartBB(CGF.Builder.GetInsertBlock()) {}
  846. void begin(CodeGenFunction &CGF) {
  847. assert(CGF.OutermostConditional != this);
  848. if (!CGF.OutermostConditional)
  849. CGF.OutermostConditional = this;
  850. }
  851. void end(CodeGenFunction &CGF) {
  852. assert(CGF.OutermostConditional != nullptr);
  853. if (CGF.OutermostConditional == this)
  854. CGF.OutermostConditional = nullptr;
  855. }
  856. /// Returns a block which will be executed prior to each
  857. /// evaluation of the conditional code.
  858. llvm::BasicBlock *getStartingBlock() const {
  859. return StartBB;
  860. }
  861. };
  862. /// isInConditionalBranch - Return true if we're currently emitting
  863. /// one branch or the other of a conditional expression.
  864. bool isInConditionalBranch() const { return OutermostConditional != nullptr; }
  865. void setBeforeOutermostConditional(llvm::Value *value, Address addr) {
  866. assert(isInConditionalBranch());
  867. llvm::BasicBlock *block = OutermostConditional->getStartingBlock();
  868. auto store = new llvm::StoreInst(value, addr.getPointer(), &block->back());
  869. store->setAlignment(addr.getAlignment().getAsAlign());
  870. }
  871. /// An RAII object to record that we're evaluating a statement
  872. /// expression.
  873. class StmtExprEvaluation {
  874. CodeGenFunction &CGF;
  875. /// We have to save the outermost conditional: cleanups in a
  876. /// statement expression aren't conditional just because the
  877. /// StmtExpr is.
  878. ConditionalEvaluation *SavedOutermostConditional;
  879. public:
  880. StmtExprEvaluation(CodeGenFunction &CGF)
  881. : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) {
  882. CGF.OutermostConditional = nullptr;
  883. }
  884. ~StmtExprEvaluation() {
  885. CGF.OutermostConditional = SavedOutermostConditional;
  886. CGF.EnsureInsertPoint();
  887. }
  888. };
  889. /// An object which temporarily prevents a value from being
  890. /// destroyed by aggressive peephole optimizations that assume that
  891. /// all uses of a value have been realized in the IR.
  892. class PeepholeProtection {
  893. llvm::Instruction *Inst;
  894. friend class CodeGenFunction;
  895. public:
  896. PeepholeProtection() : Inst(nullptr) {}
  897. };
  898. /// A non-RAII class containing all the information about a bound
  899. /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for
  900. /// this which makes individual mappings very simple; using this
  901. /// class directly is useful when you have a variable number of
  902. /// opaque values or don't want the RAII functionality for some
  903. /// reason.
  904. class OpaqueValueMappingData {
  905. const OpaqueValueExpr *OpaqueValue;
  906. bool BoundLValue;
  907. CodeGenFunction::PeepholeProtection Protection;
  908. OpaqueValueMappingData(const OpaqueValueExpr *ov,
  909. bool boundLValue)
  910. : OpaqueValue(ov), BoundLValue(boundLValue) {}
  911. public:
  912. OpaqueValueMappingData() : OpaqueValue(nullptr) {}
  913. static bool shouldBindAsLValue(const Expr *expr) {
  914. // gl-values should be bound as l-values for obvious reasons.
  915. // Records should be bound as l-values because IR generation
  916. // always keeps them in memory. Expressions of function type
  917. // act exactly like l-values but are formally required to be
  918. // r-values in C.
  919. return expr->isGLValue() ||
  920. expr->getType()->isFunctionType() ||
  921. hasAggregateEvaluationKind(expr->getType());
  922. }
  923. static OpaqueValueMappingData bind(CodeGenFunction &CGF,
  924. const OpaqueValueExpr *ov,
  925. const Expr *e) {
  926. if (shouldBindAsLValue(ov))
  927. return bind(CGF, ov, CGF.EmitLValue(e));
  928. return bind(CGF, ov, CGF.EmitAnyExpr(e));
  929. }
  930. static OpaqueValueMappingData bind(CodeGenFunction &CGF,
  931. const OpaqueValueExpr *ov,
  932. const LValue &lv) {
  933. assert(shouldBindAsLValue(ov));
  934. CGF.OpaqueLValues.insert(std::make_pair(ov, lv));
  935. return OpaqueValueMappingData(ov, true);
  936. }
  937. static OpaqueValueMappingData bind(CodeGenFunction &CGF,
  938. const OpaqueValueExpr *ov,
  939. const RValue &rv) {
  940. assert(!shouldBindAsLValue(ov));
  941. CGF.OpaqueRValues.insert(std::make_pair(ov, rv));
  942. OpaqueValueMappingData data(ov, false);
  943. // Work around an extremely aggressive peephole optimization in
  944. // EmitScalarConversion which assumes that all other uses of a
  945. // value are extant.
  946. data.Protection = CGF.protectFromPeepholes(rv);
  947. return data;
  948. }
  949. bool isValid() const { return OpaqueValue != nullptr; }
  950. void clear() { OpaqueValue = nullptr; }
  951. void unbind(CodeGenFunction &CGF) {
  952. assert(OpaqueValue && "no data to unbind!");
  953. if (BoundLValue) {
  954. CGF.OpaqueLValues.erase(OpaqueValue);
  955. } else {
  956. CGF.OpaqueRValues.erase(OpaqueValue);
  957. CGF.unprotectFromPeepholes(Protection);
  958. }
  959. }
  960. };
  961. /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
  962. class OpaqueValueMapping {
  963. CodeGenFunction &CGF;
  964. OpaqueValueMappingData Data;
  965. public:
  966. static bool shouldBindAsLValue(const Expr *expr) {
  967. return OpaqueValueMappingData::shouldBindAsLValue(expr);
  968. }
  969. /// Build the opaque value mapping for the given conditional
  970. /// operator if it's the GNU ?: extension. This is a common
  971. /// enough pattern that the convenience operator is really
  972. /// helpful.
  973. ///
  974. OpaqueValueMapping(CodeGenFunction &CGF,
  975. const AbstractConditionalOperator *op) : CGF(CGF) {
  976. if (isa<ConditionalOperator>(op))
  977. // Leave Data empty.
  978. return;
  979. const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op);
  980. Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(),
  981. e->getCommon());
  982. }
  983. /// Build the opaque value mapping for an OpaqueValueExpr whose source
  984. /// expression is set to the expression the OVE represents.
  985. OpaqueValueMapping(CodeGenFunction &CGF, const OpaqueValueExpr *OV)
  986. : CGF(CGF) {
  987. if (OV) {
  988. assert(OV->getSourceExpr() && "wrong form of OpaqueValueMapping used "
  989. "for OVE with no source expression");
  990. Data = OpaqueValueMappingData::bind(CGF, OV, OV->getSourceExpr());
  991. }
  992. }
  993. OpaqueValueMapping(CodeGenFunction &CGF,
  994. const OpaqueValueExpr *opaqueValue,
  995. LValue lvalue)
  996. : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) {
  997. }
  998. OpaqueValueMapping(CodeGenFunction &CGF,
  999. const OpaqueValueExpr *opaqueValue,
  1000. RValue rvalue)
  1001. : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) {
  1002. }
  1003. void pop() {
  1004. Data.unbind(CGF);
  1005. Data.clear();
  1006. }
  1007. ~OpaqueValueMapping() {
  1008. if (Data.isValid()) Data.unbind(CGF);
  1009. }
  1010. };
  1011. private:
  1012. CGDebugInfo *DebugInfo;
  1013. /// Used to create unique names for artificial VLA size debug info variables.
  1014. unsigned VLAExprCounter = 0;
  1015. bool DisableDebugInfo = false;
  1016. /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
  1017. /// calling llvm.stacksave for multiple VLAs in the same scope.
  1018. bool DidCallStackSave = false;
  1019. /// IndirectBranch - The first time an indirect goto is seen we create a block
  1020. /// with an indirect branch. Every time we see the address of a label taken,
  1021. /// we add the label to the indirect goto. Every subsequent indirect goto is
  1022. /// codegen'd as a jump to the IndirectBranch's basic block.
  1023. llvm::IndirectBrInst *IndirectBranch = nullptr;
  1024. /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
  1025. /// decls.
  1026. DeclMapTy LocalDeclMap;
  1027. // Keep track of the cleanups for callee-destructed parameters pushed to the
  1028. // cleanup stack so that they can be deactivated later.
  1029. llvm::DenseMap<const ParmVarDecl *, EHScopeStack::stable_iterator>
  1030. CalleeDestructedParamCleanups;
  1031. /// SizeArguments - If a ParmVarDecl had the pass_object_size attribute, this
  1032. /// will contain a mapping from said ParmVarDecl to its implicit "object_size"
  1033. /// parameter.
  1034. llvm::SmallDenseMap<const ParmVarDecl *, const ImplicitParamDecl *, 2>
  1035. SizeArguments;
  1036. /// Track escaped local variables with auto storage. Used during SEH
  1037. /// outlining to produce a call to llvm.localescape.
  1038. llvm::DenseMap<llvm::AllocaInst *, int> EscapedLocals;
  1039. /// LabelMap - This keeps track of the LLVM basic block for each C label.
  1040. llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap;
  1041. // BreakContinueStack - This keeps track of where break and continue
  1042. // statements should jump to.
  1043. struct BreakContinue {
  1044. BreakContinue(JumpDest Break, JumpDest Continue)
  1045. : BreakBlock(Break), ContinueBlock(Continue) {}
  1046. JumpDest BreakBlock;
  1047. JumpDest ContinueBlock;
  1048. };
  1049. SmallVector<BreakContinue, 8> BreakContinueStack;
  1050. /// Handles cancellation exit points in OpenMP-related constructs.
  1051. class OpenMPCancelExitStack {
  1052. /// Tracks cancellation exit point and join point for cancel-related exit
  1053. /// and normal exit.
  1054. struct CancelExit {
  1055. CancelExit() = default;
  1056. CancelExit(OpenMPDirectiveKind Kind, JumpDest ExitBlock,
  1057. JumpDest ContBlock)
  1058. : Kind(Kind), ExitBlock(ExitBlock), ContBlock(ContBlock) {}
  1059. OpenMPDirectiveKind Kind = OMPD_unknown;
  1060. /// true if the exit block has been emitted already by the special
  1061. /// emitExit() call, false if the default codegen is used.
  1062. bool HasBeenEmitted = false;
  1063. JumpDest ExitBlock;
  1064. JumpDest ContBlock;
  1065. };
  1066. SmallVector<CancelExit, 8> Stack;
  1067. public:
  1068. OpenMPCancelExitStack() : Stack(1) {}
  1069. ~OpenMPCancelExitStack() = default;
  1070. /// Fetches the exit block for the current OpenMP construct.
  1071. JumpDest getExitBlock() const { return Stack.back().ExitBlock; }
  1072. /// Emits exit block with special codegen procedure specific for the related
  1073. /// OpenMP construct + emits code for normal construct cleanup.
  1074. void emitExit(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
  1075. const llvm::function_ref<void(CodeGenFunction &)> CodeGen) {
  1076. if (Stack.back().Kind == Kind && getExitBlock().isValid()) {
  1077. assert(CGF.getOMPCancelDestination(Kind).isValid());
  1078. assert(CGF.HaveInsertPoint());
  1079. assert(!Stack.back().HasBeenEmitted);
  1080. auto IP = CGF.Builder.saveAndClearIP();
  1081. CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
  1082. CodeGen(CGF);
  1083. CGF.EmitBranch(Stack.back().ContBlock.getBlock());
  1084. CGF.Builder.restoreIP(IP);
  1085. Stack.back().HasBeenEmitted = true;
  1086. }
  1087. CodeGen(CGF);
  1088. }
  1089. /// Enter the cancel supporting \a Kind construct.
  1090. /// \param Kind OpenMP directive that supports cancel constructs.
  1091. /// \param HasCancel true, if the construct has inner cancel directive,
  1092. /// false otherwise.
  1093. void enter(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, bool HasCancel) {
  1094. Stack.push_back({Kind,
  1095. HasCancel ? CGF.getJumpDestInCurrentScope("cancel.exit")
  1096. : JumpDest(),
  1097. HasCancel ? CGF.getJumpDestInCurrentScope("cancel.cont")
  1098. : JumpDest()});
  1099. }
  1100. /// Emits default exit point for the cancel construct (if the special one
  1101. /// has not be used) + join point for cancel/normal exits.
  1102. void exit(CodeGenFunction &CGF) {
  1103. if (getExitBlock().isValid()) {
  1104. assert(CGF.getOMPCancelDestination(Stack.back().Kind).isValid());
  1105. bool HaveIP = CGF.HaveInsertPoint();
  1106. if (!Stack.back().HasBeenEmitted) {
  1107. if (HaveIP)
  1108. CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
  1109. CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
  1110. CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
  1111. }
  1112. CGF.EmitBlock(Stack.back().ContBlock.getBlock());
  1113. if (!HaveIP) {
  1114. CGF.Builder.CreateUnreachable();
  1115. CGF.Builder.ClearInsertionPoint();
  1116. }
  1117. }
  1118. Stack.pop_back();
  1119. }
  1120. };
  1121. OpenMPCancelExitStack OMPCancelStack;
  1122. CodeGenPGO PGO;
  1123. /// Calculate branch weights appropriate for PGO data
  1124. llvm::MDNode *createProfileWeights(uint64_t TrueCount, uint64_t FalseCount);
  1125. llvm::MDNode *createProfileWeights(ArrayRef<uint64_t> Weights);
  1126. llvm::MDNode *createProfileWeightsForLoop(const Stmt *Cond,
  1127. uint64_t LoopCount);
  1128. public:
  1129. /// Increment the profiler's counter for the given statement by \p StepV.
  1130. /// If \p StepV is null, the default increment is 1.
  1131. void incrementProfileCounter(const Stmt *S, llvm::Value *StepV = nullptr) {
  1132. if (CGM.getCodeGenOpts().hasProfileClangInstr())
  1133. PGO.emitCounterIncrement(Builder, S, StepV);
  1134. PGO.setCurrentStmt(S);
  1135. }
  1136. /// Get the profiler's count for the given statement.
  1137. uint64_t getProfileCount(const Stmt *S) {
  1138. Optional<uint64_t> Count = PGO.getStmtCount(S);
  1139. if (!Count.hasValue())
  1140. return 0;
  1141. return *Count;
  1142. }
  1143. /// Set the profiler's current count.
  1144. void setCurrentProfileCount(uint64_t Count) {
  1145. PGO.setCurrentRegionCount(Count);
  1146. }
  1147. /// Get the profiler's current count. This is generally the count for the most
  1148. /// recently incremented counter.
  1149. uint64_t getCurrentProfileCount() {
  1150. return PGO.getCurrentRegionCount();
  1151. }
  1152. private:
  1153. /// SwitchInsn - This is nearest current switch instruction. It is null if
  1154. /// current context is not in a switch.
  1155. llvm::SwitchInst *SwitchInsn = nullptr;
  1156. /// The branch weights of SwitchInsn when doing instrumentation based PGO.
  1157. SmallVector<uint64_t, 16> *SwitchWeights = nullptr;
  1158. /// CaseRangeBlock - This block holds if condition check for last case
  1159. /// statement range in current switch instruction.
  1160. llvm::BasicBlock *CaseRangeBlock = nullptr;
  1161. /// OpaqueLValues - Keeps track of the current set of opaque value
  1162. /// expressions.
  1163. llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
  1164. llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
  1165. // VLASizeMap - This keeps track of the associated size for each VLA type.
  1166. // We track this by the size expression rather than the type itself because
  1167. // in certain situations, like a const qualifier applied to an VLA typedef,
  1168. // multiple VLA types can share the same size expression.
  1169. // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
  1170. // enter/leave scopes.
  1171. llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
  1172. /// A block containing a single 'unreachable' instruction. Created
  1173. /// lazily by getUnreachableBlock().
  1174. llvm::BasicBlock *UnreachableBlock = nullptr;
  1175. /// Counts of the number return expressions in the function.
  1176. unsigned NumReturnExprs = 0;
  1177. /// Count the number of simple (constant) return expressions in the function.
  1178. unsigned NumSimpleReturnExprs = 0;
  1179. /// The last regular (non-return) debug location (breakpoint) in the function.
  1180. SourceLocation LastStopPoint;
  1181. public:
  1182. /// Source location information about the default argument or member
  1183. /// initializer expression we're evaluating, if any.
  1184. CurrentSourceLocExprScope CurSourceLocExprScope;
  1185. using SourceLocExprScopeGuard =
  1186. CurrentSourceLocExprScope::SourceLocExprScopeGuard;
  1187. /// A scope within which we are constructing the fields of an object which
  1188. /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use
  1189. /// if we need to evaluate a CXXDefaultInitExpr within the evaluation.
  1190. class FieldConstructionScope {
  1191. public:
  1192. FieldConstructionScope(CodeGenFunction &CGF, Address This)
  1193. : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) {
  1194. CGF.CXXDefaultInitExprThis = This;
  1195. }
  1196. ~FieldConstructionScope() {
  1197. CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis;
  1198. }
  1199. private:
  1200. CodeGenFunction &CGF;
  1201. Address OldCXXDefaultInitExprThis;
  1202. };
  1203. /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this'
  1204. /// is overridden to be the object under construction.
  1205. class CXXDefaultInitExprScope {
  1206. public:
  1207. CXXDefaultInitExprScope(CodeGenFunction &CGF, const CXXDefaultInitExpr *E)
  1208. : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue),
  1209. OldCXXThisAlignment(CGF.CXXThisAlignment),
  1210. SourceLocScope(E, CGF.CurSourceLocExprScope) {
  1211. CGF.CXXThisValue = CGF.CXXDefaultInitExprThis.getPointer();
  1212. CGF.CXXThisAlignment = CGF.CXXDefaultInitExprThis.getAlignment();
  1213. }
  1214. ~CXXDefaultInitExprScope() {
  1215. CGF.CXXThisValue = OldCXXThisValue;
  1216. CGF.CXXThisAlignment = OldCXXThisAlignment;
  1217. }
  1218. public:
  1219. CodeGenFunction &CGF;
  1220. llvm::Value *OldCXXThisValue;
  1221. CharUnits OldCXXThisAlignment;
  1222. SourceLocExprScopeGuard SourceLocScope;
  1223. };
  1224. struct CXXDefaultArgExprScope : SourceLocExprScopeGuard {
  1225. CXXDefaultArgExprScope(CodeGenFunction &CGF, const CXXDefaultArgExpr *E)
  1226. : SourceLocExprScopeGuard(E, CGF.CurSourceLocExprScope) {}
  1227. };
  1228. /// The scope of an ArrayInitLoopExpr. Within this scope, the value of the
  1229. /// current loop index is overridden.
  1230. class ArrayInitLoopExprScope {
  1231. public:
  1232. ArrayInitLoopExprScope(CodeGenFunction &CGF, llvm::Value *Index)
  1233. : CGF(CGF), OldArrayInitIndex(CGF.ArrayInitIndex) {
  1234. CGF.ArrayInitIndex = Index;
  1235. }
  1236. ~ArrayInitLoopExprScope() {
  1237. CGF.ArrayInitIndex = OldArrayInitIndex;
  1238. }
  1239. private:
  1240. CodeGenFunction &CGF;
  1241. llvm::Value *OldArrayInitIndex;
  1242. };
  1243. class InlinedInheritingConstructorScope {
  1244. public:
  1245. InlinedInheritingConstructorScope(CodeGenFunction &CGF, GlobalDecl GD)
  1246. : CGF(CGF), OldCurGD(CGF.CurGD), OldCurFuncDecl(CGF.CurFuncDecl),
  1247. OldCurCodeDecl(CGF.CurCodeDecl),
  1248. OldCXXABIThisDecl(CGF.CXXABIThisDecl),
  1249. OldCXXABIThisValue(CGF.CXXABIThisValue),
  1250. OldCXXThisValue(CGF.CXXThisValue),
  1251. OldCXXABIThisAlignment(CGF.CXXABIThisAlignment),
  1252. OldCXXThisAlignment(CGF.CXXThisAlignment),
  1253. OldReturnValue(CGF.ReturnValue), OldFnRetTy(CGF.FnRetTy),
  1254. OldCXXInheritedCtorInitExprArgs(
  1255. std::move(CGF.CXXInheritedCtorInitExprArgs)) {
  1256. CGF.CurGD = GD;
  1257. CGF.CurFuncDecl = CGF.CurCodeDecl =
  1258. cast<CXXConstructorDecl>(GD.getDecl());
  1259. CGF.CXXABIThisDecl = nullptr;
  1260. CGF.CXXABIThisValue = nullptr;
  1261. CGF.CXXThisValue = nullptr;
  1262. CGF.CXXABIThisAlignment = CharUnits();
  1263. CGF.CXXThisAlignment = CharUnits();
  1264. CGF.ReturnValue = Address::invalid();
  1265. CGF.FnRetTy = QualType();
  1266. CGF.CXXInheritedCtorInitExprArgs.clear();
  1267. }
  1268. ~InlinedInheritingConstructorScope() {
  1269. CGF.CurGD = OldCurGD;
  1270. CGF.CurFuncDecl = OldCurFuncDecl;
  1271. CGF.CurCodeDecl = OldCurCodeDecl;
  1272. CGF.CXXABIThisDecl = OldCXXABIThisDecl;
  1273. CGF.CXXABIThisValue = OldCXXABIThisValue;
  1274. CGF.CXXThisValue = OldCXXThisValue;
  1275. CGF.CXXABIThisAlignment = OldCXXABIThisAlignment;
  1276. CGF.CXXThisAlignment = OldCXXThisAlignment;
  1277. CGF.ReturnValue = OldReturnValue;
  1278. CGF.FnRetTy = OldFnRetTy;
  1279. CGF.CXXInheritedCtorInitExprArgs =
  1280. std::move(OldCXXInheritedCtorInitExprArgs);
  1281. }
  1282. private:
  1283. CodeGenFunction &CGF;
  1284. GlobalDecl OldCurGD;
  1285. const Decl *OldCurFuncDecl;
  1286. const Decl *OldCurCodeDecl;
  1287. ImplicitParamDecl *OldCXXABIThisDecl;
  1288. llvm::Value *OldCXXABIThisValue;
  1289. llvm::Value *OldCXXThisValue;
  1290. CharUnits OldCXXABIThisAlignment;
  1291. CharUnits OldCXXThisAlignment;
  1292. Address OldReturnValue;
  1293. QualType OldFnRetTy;
  1294. CallArgList OldCXXInheritedCtorInitExprArgs;
  1295. };
  1296. private:
  1297. /// CXXThisDecl - When generating code for a C++ member function,
  1298. /// this will hold the implicit 'this' declaration.
  1299. ImplicitParamDecl *CXXABIThisDecl = nullptr;
  1300. llvm::Value *CXXABIThisValue = nullptr;
  1301. llvm::Value *CXXThisValue = nullptr;
  1302. CharUnits CXXABIThisAlignment;
  1303. CharUnits CXXThisAlignment;
  1304. /// The value of 'this' to use when evaluating CXXDefaultInitExprs within
  1305. /// this expression.
  1306. Address CXXDefaultInitExprThis = Address::invalid();
  1307. /// The current array initialization index when evaluating an
  1308. /// ArrayInitIndexExpr within an ArrayInitLoopExpr.
  1309. llvm::Value *ArrayInitIndex = nullptr;
  1310. /// The values of function arguments to use when evaluating
  1311. /// CXXInheritedCtorInitExprs within this context.
  1312. CallArgList CXXInheritedCtorInitExprArgs;
  1313. /// CXXStructorImplicitParamDecl - When generating code for a constructor or
  1314. /// destructor, this will hold the implicit argument (e.g. VTT).
  1315. ImplicitParamDecl *CXXStructorImplicitParamDecl = nullptr;
  1316. llvm::Value *CXXStructorImplicitParamValue = nullptr;
  1317. /// OutermostConditional - Points to the outermost active
  1318. /// conditional control. This is used so that we know if a
  1319. /// temporary should be destroyed conditionally.
  1320. ConditionalEvaluation *OutermostConditional = nullptr;
  1321. /// The current lexical scope.
  1322. LexicalScope *CurLexicalScope = nullptr;
  1323. /// The current source location that should be used for exception
  1324. /// handling code.
  1325. SourceLocation CurEHLocation;
  1326. /// BlockByrefInfos - For each __block variable, contains
  1327. /// information about the layout of the variable.
  1328. llvm::DenseMap<const ValueDecl *, BlockByrefInfo> BlockByrefInfos;
  1329. /// Used by -fsanitize=nullability-return to determine whether the return
  1330. /// value can be checked.
  1331. llvm::Value *RetValNullabilityPrecondition = nullptr;
  1332. /// Check if -fsanitize=nullability-return instrumentation is required for
  1333. /// this function.
  1334. bool requiresReturnValueNullabilityCheck() const {
  1335. return RetValNullabilityPrecondition;
  1336. }
  1337. /// Used to store precise source locations for return statements by the
  1338. /// runtime return value checks.
  1339. Address ReturnLocation = Address::invalid();
  1340. /// Check if the return value of this function requires sanitization.
  1341. bool requiresReturnValueCheck() const {
  1342. return requiresReturnValueNullabilityCheck() ||
  1343. (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
  1344. CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>());
  1345. }
  1346. llvm::BasicBlock *TerminateLandingPad = nullptr;
  1347. llvm::BasicBlock *TerminateHandler = nullptr;
  1348. llvm::BasicBlock *TrapBB = nullptr;
  1349. /// Terminate funclets keyed by parent funclet pad.
  1350. llvm::MapVector<llvm::Value *, llvm::BasicBlock *> TerminateFunclets;
  1351. /// Largest vector width used in ths function. Will be used to create a
  1352. /// function attribute.
  1353. unsigned LargestVectorWidth = 0;
  1354. /// True if we need emit the life-time markers.
  1355. const bool ShouldEmitLifetimeMarkers;
  1356. /// Add OpenCL kernel arg metadata and the kernel attribute metadata to
  1357. /// the function metadata.
  1358. void EmitOpenCLKernelMetadata(const FunctionDecl *FD,
  1359. llvm::Function *Fn);
  1360. public:
  1361. CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false);
  1362. ~CodeGenFunction();
  1363. CodeGenTypes &getTypes() const { return CGM.getTypes(); }
  1364. ASTContext &getContext() const { return CGM.getContext(); }
  1365. CGDebugInfo *getDebugInfo() {
  1366. if (DisableDebugInfo)
  1367. return nullptr;
  1368. return DebugInfo;
  1369. }
  1370. void disableDebugInfo() { DisableDebugInfo = true; }
  1371. void enableDebugInfo() { DisableDebugInfo = false; }
  1372. bool shouldUseFusedARCCalls() {
  1373. return CGM.getCodeGenOpts().OptimizationLevel == 0;
  1374. }
  1375. const LangOptions &getLangOpts() const { return CGM.getLangOpts(); }
  1376. /// Returns a pointer to the function's exception object and selector slot,
  1377. /// which is assigned in every landing pad.
  1378. Address getExceptionSlot();
  1379. Address getEHSelectorSlot();
  1380. /// Returns the contents of the function's exception object and selector
  1381. /// slots.
  1382. llvm::Value *getExceptionFromSlot();
  1383. llvm::Value *getSelectorFromSlot();
  1384. Address getNormalCleanupDestSlot();
  1385. llvm::BasicBlock *getUnreachableBlock() {
  1386. if (!UnreachableBlock) {
  1387. UnreachableBlock = createBasicBlock("unreachable");
  1388. new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
  1389. }
  1390. return UnreachableBlock;
  1391. }
  1392. llvm::BasicBlock *getInvokeDest() {
  1393. if (!EHStack.requiresLandingPad()) return nullptr;
  1394. return getInvokeDestImpl();
  1395. }
  1396. bool currentFunctionUsesSEHTry() const { return CurSEHParent != nullptr; }
  1397. const TargetInfo &getTarget() const { return Target; }
  1398. llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
  1399. const TargetCodeGenInfo &getTargetHooks() const {
  1400. return CGM.getTargetCodeGenInfo();
  1401. }
  1402. //===--------------------------------------------------------------------===//
  1403. // Cleanups
  1404. //===--------------------------------------------------------------------===//
  1405. typedef void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty);
  1406. void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
  1407. Address arrayEndPointer,
  1408. QualType elementType,
  1409. CharUnits elementAlignment,
  1410. Destroyer *destroyer);
  1411. void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
  1412. llvm::Value *arrayEnd,
  1413. QualType elementType,
  1414. CharUnits elementAlignment,
  1415. Destroyer *destroyer);
  1416. void pushDestroy(QualType::DestructionKind dtorKind,
  1417. Address addr, QualType type);
  1418. void pushEHDestroy(QualType::DestructionKind dtorKind,
  1419. Address addr, QualType type);
  1420. void pushDestroy(CleanupKind kind, Address addr, QualType type,
  1421. Destroyer *destroyer, bool useEHCleanupForArray);
  1422. void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr,
  1423. QualType type, Destroyer *destroyer,
  1424. bool useEHCleanupForArray);
  1425. void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
  1426. llvm::Value *CompletePtr,
  1427. QualType ElementType);
  1428. void pushStackRestore(CleanupKind kind, Address SPMem);
  1429. void emitDestroy(Address addr, QualType type, Destroyer *destroyer,
  1430. bool useEHCleanupForArray);
  1431. llvm::Function *generateDestroyHelper(Address addr, QualType type,
  1432. Destroyer *destroyer,
  1433. bool useEHCleanupForArray,
  1434. const VarDecl *VD);
  1435. void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
  1436. QualType elementType, CharUnits elementAlign,
  1437. Destroyer *destroyer,
  1438. bool checkZeroLength, bool useEHCleanup);
  1439. Destroyer *getDestroyer(QualType::DestructionKind destructionKind);
  1440. /// Determines whether an EH cleanup is required to destroy a type
  1441. /// with the given destruction kind.
  1442. bool needsEHCleanup(QualType::DestructionKind kind) {
  1443. switch (kind) {
  1444. case QualType::DK_none:
  1445. return false;
  1446. case QualType::DK_cxx_destructor:
  1447. case QualType::DK_objc_weak_lifetime:
  1448. case QualType::DK_nontrivial_c_struct:
  1449. return getLangOpts().Exceptions;
  1450. case QualType::DK_objc_strong_lifetime:
  1451. return getLangOpts().Exceptions &&
  1452. CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
  1453. }
  1454. llvm_unreachable("bad destruction kind");
  1455. }
  1456. CleanupKind getCleanupKind(QualType::DestructionKind kind) {
  1457. return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup);
  1458. }
  1459. //===--------------------------------------------------------------------===//
  1460. // Objective-C
  1461. //===--------------------------------------------------------------------===//
  1462. void GenerateObjCMethod(const ObjCMethodDecl *OMD);
  1463. void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD);
  1464. /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
  1465. void GenerateObjCGetter(ObjCImplementationDecl *IMP,
  1466. const ObjCPropertyImplDecl *PID);
  1467. void generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
  1468. const ObjCPropertyImplDecl *propImpl,
  1469. const ObjCMethodDecl *GetterMothodDecl,
  1470. llvm::Constant *AtomicHelperFn);
  1471. void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
  1472. ObjCMethodDecl *MD, bool ctor);
  1473. /// GenerateObjCSetter - Synthesize an Objective-C property setter function
  1474. /// for the given property.
  1475. void GenerateObjCSetter(ObjCImplementationDecl *IMP,
  1476. const ObjCPropertyImplDecl *PID);
  1477. void generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
  1478. const ObjCPropertyImplDecl *propImpl,
  1479. llvm::Constant *AtomicHelperFn);
  1480. //===--------------------------------------------------------------------===//
  1481. // Block Bits
  1482. //===--------------------------------------------------------------------===//
  1483. /// Emit block literal.
  1484. /// \return an LLVM value which is a pointer to a struct which contains
  1485. /// information about the block, including the block invoke function, the
  1486. /// captured variables, etc.
  1487. llvm::Value *EmitBlockLiteral(const BlockExpr *);
  1488. static void destroyBlockInfos(CGBlockInfo *info);
  1489. llvm::Function *GenerateBlockFunction(GlobalDecl GD,
  1490. const CGBlockInfo &Info,
  1491. const DeclMapTy &ldm,
  1492. bool IsLambdaConversionToBlock,
  1493. bool BuildGlobalBlock);
  1494. /// Check if \p T is a C++ class that has a destructor that can throw.
  1495. static bool cxxDestructorCanThrow(QualType T);
  1496. llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
  1497. llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
  1498. llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction(
  1499. const ObjCPropertyImplDecl *PID);
  1500. llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction(
  1501. const ObjCPropertyImplDecl *PID);
  1502. llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty);
  1503. void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags,
  1504. bool CanThrow);
  1505. class AutoVarEmission;
  1506. void emitByrefStructureInit(const AutoVarEmission &emission);
  1507. /// Enter a cleanup to destroy a __block variable. Note that this
  1508. /// cleanup should be a no-op if the variable hasn't left the stack
  1509. /// yet; if a cleanup is required for the variable itself, that needs
  1510. /// to be done externally.
  1511. ///
  1512. /// \param Kind Cleanup kind.
  1513. ///
  1514. /// \param Addr When \p LoadBlockVarAddr is false, the address of the __block
  1515. /// structure that will be passed to _Block_object_dispose. When
  1516. /// \p LoadBlockVarAddr is true, the address of the field of the block
  1517. /// structure that holds the address of the __block structure.
  1518. ///
  1519. /// \param Flags The flag that will be passed to _Block_object_dispose.
  1520. ///
  1521. /// \param LoadBlockVarAddr Indicates whether we need to emit a load from
  1522. /// \p Addr to get the address of the __block structure.
  1523. void enterByrefCleanup(CleanupKind Kind, Address Addr, BlockFieldFlags Flags,
  1524. bool LoadBlockVarAddr, bool CanThrow);
  1525. void setBlockContextParameter(const ImplicitParamDecl *D, unsigned argNum,
  1526. llvm::Value *ptr);
  1527. Address LoadBlockStruct();
  1528. Address GetAddrOfBlockDecl(const VarDecl *var);
  1529. /// BuildBlockByrefAddress - Computes the location of the
  1530. /// data in a variable which is declared as __block.
  1531. Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V,
  1532. bool followForward = true);
  1533. Address emitBlockByrefAddress(Address baseAddr,
  1534. const BlockByrefInfo &info,
  1535. bool followForward,
  1536. const llvm::Twine &name);
  1537. const BlockByrefInfo &getBlockByrefInfo(const VarDecl *var);
  1538. QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args);
  1539. void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
  1540. const CGFunctionInfo &FnInfo);
  1541. /// Annotate the function with an attribute that disables TSan checking at
  1542. /// runtime.
  1543. void markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn);
  1544. /// Emit code for the start of a function.
  1545. /// \param Loc The location to be associated with the function.
  1546. /// \param StartLoc The location of the function body.
  1547. void StartFunction(GlobalDecl GD,
  1548. QualType RetTy,
  1549. llvm::Function *Fn,
  1550. const CGFunctionInfo &FnInfo,
  1551. const FunctionArgList &Args,
  1552. SourceLocation Loc = SourceLocation(),
  1553. SourceLocation StartLoc = SourceLocation());
  1554. static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor);
  1555. void EmitConstructorBody(FunctionArgList &Args);
  1556. void EmitDestructorBody(FunctionArgList &Args);
  1557. void emitImplicitAssignmentOperatorBody(FunctionArgList &Args);
  1558. void EmitFunctionBody(const Stmt *Body);
  1559. void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S);
  1560. void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator,
  1561. CallArgList &CallArgs);
  1562. void EmitLambdaBlockInvokeBody();
  1563. void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD);
  1564. void EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD);
  1565. void EmitLambdaVLACapture(const VariableArrayType *VAT, LValue LV) {
  1566. EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
  1567. }
  1568. void EmitAsanPrologueOrEpilogue(bool Prologue);
  1569. /// Emit the unified return block, trying to avoid its emission when
  1570. /// possible.
  1571. /// \return The debug location of the user written return statement if the
  1572. /// return block is is avoided.
  1573. llvm::DebugLoc EmitReturnBlock();
  1574. /// FinishFunction - Complete IR generation of the current function. It is
  1575. /// legal to call this function even if there is no current insertion point.
  1576. void FinishFunction(SourceLocation EndLoc=SourceLocation());
  1577. void StartThunk(llvm::Function *Fn, GlobalDecl GD,
  1578. const CGFunctionInfo &FnInfo, bool IsUnprototyped);
  1579. void EmitCallAndReturnForThunk(llvm::FunctionCallee Callee,
  1580. const ThunkInfo *Thunk, bool IsUnprototyped);
  1581. void FinishThunk();
  1582. /// Emit a musttail call for a thunk with a potentially adjusted this pointer.
  1583. void EmitMustTailThunk(GlobalDecl GD, llvm::Value *AdjustedThisPtr,
  1584. llvm::FunctionCallee Callee);
  1585. /// Generate a thunk for the given method.
  1586. void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
  1587. GlobalDecl GD, const ThunkInfo &Thunk,
  1588. bool IsUnprototyped);
  1589. llvm::Function *GenerateVarArgsThunk(llvm::Function *Fn,
  1590. const CGFunctionInfo &FnInfo,
  1591. GlobalDecl GD, const ThunkInfo &Thunk);
  1592. void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
  1593. FunctionArgList &Args);
  1594. void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init);
  1595. /// Struct with all information about dynamic [sub]class needed to set vptr.
  1596. struct VPtr {
  1597. BaseSubobject Base;
  1598. const CXXRecordDecl *NearestVBase;
  1599. CharUnits OffsetFromNearestVBase;
  1600. const CXXRecordDecl *VTableClass;
  1601. };
  1602. /// Initialize the vtable pointer of the given subobject.
  1603. void InitializeVTablePointer(const VPtr &vptr);
  1604. typedef llvm::SmallVector<VPtr, 4> VPtrsVector;
  1605. typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
  1606. VPtrsVector getVTablePointers(const CXXRecordDecl *VTableClass);
  1607. void getVTablePointers(BaseSubobject Base, const CXXRecordDecl *NearestVBase,
  1608. CharUnits OffsetFromNearestVBase,
  1609. bool BaseIsNonVirtualPrimaryBase,
  1610. const CXXRecordDecl *VTableClass,
  1611. VisitedVirtualBasesSetTy &VBases, VPtrsVector &vptrs);
  1612. void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
  1613. /// GetVTablePtr - Return the Value of the vtable pointer member pointed
  1614. /// to by This.
  1615. llvm::Value *GetVTablePtr(Address This, llvm::Type *VTableTy,
  1616. const CXXRecordDecl *VTableClass);
  1617. enum CFITypeCheckKind {
  1618. CFITCK_VCall,
  1619. CFITCK_NVCall,
  1620. CFITCK_DerivedCast,
  1621. CFITCK_UnrelatedCast,
  1622. CFITCK_ICall,
  1623. CFITCK_NVMFCall,
  1624. CFITCK_VMFCall,
  1625. };
  1626. /// Derived is the presumed address of an object of type T after a
  1627. /// cast. If T is a polymorphic class type, emit a check that the virtual
  1628. /// table for Derived belongs to a class derived from T.
  1629. void EmitVTablePtrCheckForCast(QualType T, llvm::Value *Derived,
  1630. bool MayBeNull, CFITypeCheckKind TCK,
  1631. SourceLocation Loc);
  1632. /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable.
  1633. /// If vptr CFI is enabled, emit a check that VTable is valid.
  1634. void EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, llvm::Value *VTable,
  1635. CFITypeCheckKind TCK, SourceLocation Loc);
  1636. /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for
  1637. /// RD using llvm.type.test.
  1638. void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable,
  1639. CFITypeCheckKind TCK, SourceLocation Loc);
  1640. /// If whole-program virtual table optimization is enabled, emit an assumption
  1641. /// that VTable is a member of RD's type identifier. Or, if vptr CFI is
  1642. /// enabled, emit a check that VTable is a member of RD's type identifier.
  1643. void EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
  1644. llvm::Value *VTable, SourceLocation Loc);
  1645. /// Returns whether we should perform a type checked load when loading a
  1646. /// virtual function for virtual calls to members of RD. This is generally
  1647. /// true when both vcall CFI and whole-program-vtables are enabled.
  1648. bool ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD);
  1649. /// Emit a type checked load from the given vtable.
  1650. llvm::Value *EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD, llvm::Value *VTable,
  1651. uint64_t VTableByteOffset);
  1652. /// EnterDtorCleanups - Enter the cleanups necessary to complete the
  1653. /// given phase of destruction for a destructor. The end result
  1654. /// should call destructors on members and base classes in reverse
  1655. /// order of their construction.
  1656. void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
  1657. /// ShouldInstrumentFunction - Return true if the current function should be
  1658. /// instrumented with __cyg_profile_func_* calls
  1659. bool ShouldInstrumentFunction();
  1660. /// ShouldXRayInstrument - Return true if the current function should be
  1661. /// instrumented with XRay nop sleds.
  1662. bool ShouldXRayInstrumentFunction() const;
  1663. /// AlwaysEmitXRayCustomEvents - Return true if we must unconditionally emit
  1664. /// XRay custom event handling calls.
  1665. bool AlwaysEmitXRayCustomEvents() const;
  1666. /// AlwaysEmitXRayTypedEvents - Return true if clang must unconditionally emit
  1667. /// XRay typed event handling calls.
  1668. bool AlwaysEmitXRayTypedEvents() const;
  1669. /// Encode an address into a form suitable for use in a function prologue.
  1670. llvm::Constant *EncodeAddrForUseInPrologue(llvm::Function *F,
  1671. llvm::Constant *Addr);
  1672. /// Decode an address used in a function prologue, encoded by \c
  1673. /// EncodeAddrForUseInPrologue.
  1674. llvm::Value *DecodeAddrUsedInPrologue(llvm::Value *F,
  1675. llvm::Value *EncodedAddr);
  1676. /// EmitFunctionProlog - Emit the target specific LLVM code to load the
  1677. /// arguments for the given function. This is also responsible for naming the
  1678. /// LLVM function arguments.
  1679. void EmitFunctionProlog(const CGFunctionInfo &FI,
  1680. llvm::Function *Fn,
  1681. const FunctionArgList &Args);
  1682. /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
  1683. /// given temporary.
  1684. void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc,
  1685. SourceLocation EndLoc);
  1686. /// Emit a test that checks if the return value \p RV is nonnull.
  1687. void EmitReturnValueCheck(llvm::Value *RV);
  1688. /// EmitStartEHSpec - Emit the start of the exception spec.
  1689. void EmitStartEHSpec(const Decl *D);
  1690. /// EmitEndEHSpec - Emit the end of the exception spec.
  1691. void EmitEndEHSpec(const Decl *D);
  1692. /// getTerminateLandingPad - Return a landing pad that just calls terminate.
  1693. llvm::BasicBlock *getTerminateLandingPad();
  1694. /// getTerminateLandingPad - Return a cleanup funclet that just calls
  1695. /// terminate.
  1696. llvm::BasicBlock *getTerminateFunclet();
  1697. /// getTerminateHandler - Return a handler (not a landing pad, just
  1698. /// a catch handler) that just calls terminate. This is used when
  1699. /// a terminate scope encloses a try.
  1700. llvm::BasicBlock *getTerminateHandler();
  1701. llvm::Type *ConvertTypeForMem(QualType T);
  1702. llvm::Type *ConvertType(QualType T);
  1703. llvm::Type *ConvertType(const TypeDecl *T) {
  1704. return ConvertType(getContext().getTypeDeclType(T));
  1705. }
  1706. /// LoadObjCSelf - Load the value of self. This function is only valid while
  1707. /// generating code for an Objective-C method.
  1708. llvm::Value *LoadObjCSelf();
  1709. /// TypeOfSelfObject - Return type of object that this self represents.
  1710. QualType TypeOfSelfObject();
  1711. /// getEvaluationKind - Return the TypeEvaluationKind of QualType \c T.
  1712. static TypeEvaluationKind getEvaluationKind(QualType T);
  1713. static bool hasScalarEvaluationKind(QualType T) {
  1714. return getEvaluationKind(T) == TEK_Scalar;
  1715. }
  1716. static bool hasAggregateEvaluationKind(QualType T) {
  1717. return getEvaluationKind(T) == TEK_Aggregate;
  1718. }
  1719. /// createBasicBlock - Create an LLVM basic block.
  1720. llvm::BasicBlock *createBasicBlock(const Twine &name = "",
  1721. llvm::Function *parent = nullptr,
  1722. llvm::BasicBlock *before = nullptr) {
  1723. return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
  1724. }
  1725. /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
  1726. /// label maps to.
  1727. JumpDest getJumpDestForLabel(const LabelDecl *S);
  1728. /// SimplifyForwardingBlocks - If the given basic block is only a branch to
  1729. /// another basic block, simplify it. This assumes that no other code could
  1730. /// potentially reference the basic block.
  1731. void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
  1732. /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
  1733. /// adding a fall-through branch from the current insert block if
  1734. /// necessary. It is legal to call this function even if there is no current
  1735. /// insertion point.
  1736. ///
  1737. /// IsFinished - If true, indicates that the caller has finished emitting
  1738. /// branches to the given block and does not expect to emit code into it. This
  1739. /// means the block can be ignored if it is unreachable.
  1740. void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
  1741. /// EmitBlockAfterUses - Emit the given block somewhere hopefully
  1742. /// near its uses, and leave the insertion point in it.
  1743. void EmitBlockAfterUses(llvm::BasicBlock *BB);
  1744. /// EmitBranch - Emit a branch to the specified basic block from the current
  1745. /// insert block, taking care to avoid creation of branches from dummy
  1746. /// blocks. It is legal to call this function even if there is no current
  1747. /// insertion point.
  1748. ///
  1749. /// This function clears the current insertion point. The caller should follow
  1750. /// calls to this function with calls to Emit*Block prior to generation new
  1751. /// code.
  1752. void EmitBranch(llvm::BasicBlock *Block);
  1753. /// HaveInsertPoint - True if an insertion point is defined. If not, this
  1754. /// indicates that the current code being emitted is unreachable.
  1755. bool HaveInsertPoint() const {
  1756. return Builder.GetInsertBlock() != nullptr;
  1757. }
  1758. /// EnsureInsertPoint - Ensure that an insertion point is defined so that
  1759. /// emitted IR has a place to go. Note that by definition, if this function
  1760. /// creates a block then that block is unreachable; callers may do better to
  1761. /// detect when no insertion point is defined and simply skip IR generation.
  1762. void EnsureInsertPoint() {
  1763. if (!HaveInsertPoint())
  1764. EmitBlock(createBasicBlock());
  1765. }
  1766. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  1767. /// specified stmt yet.
  1768. void ErrorUnsupported(const Stmt *S, const char *Type);
  1769. //===--------------------------------------------------------------------===//
  1770. // Helpers
  1771. //===--------------------------------------------------------------------===//
  1772. LValue MakeAddrLValue(Address Addr, QualType T,
  1773. AlignmentSource Source = AlignmentSource::Type) {
  1774. return LValue::MakeAddr(Addr, T, getContext(), LValueBaseInfo(Source),
  1775. CGM.getTBAAAccessInfo(T));
  1776. }
  1777. LValue MakeAddrLValue(Address Addr, QualType T, LValueBaseInfo BaseInfo,
  1778. TBAAAccessInfo TBAAInfo) {
  1779. return LValue::MakeAddr(Addr, T, getContext(), BaseInfo, TBAAInfo);
  1780. }
  1781. LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment,
  1782. AlignmentSource Source = AlignmentSource::Type) {
  1783. return LValue::MakeAddr(Address(V, Alignment), T, getContext(),
  1784. LValueBaseInfo(Source), CGM.getTBAAAccessInfo(T));
  1785. }
  1786. LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment,
  1787. LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo) {
  1788. return LValue::MakeAddr(Address(V, Alignment), T, getContext(),
  1789. BaseInfo, TBAAInfo);
  1790. }
  1791. LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T);
  1792. LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T);
  1793. CharUnits getNaturalTypeAlignment(QualType T,
  1794. LValueBaseInfo *BaseInfo = nullptr,
  1795. TBAAAccessInfo *TBAAInfo = nullptr,
  1796. bool forPointeeType = false);
  1797. CharUnits getNaturalPointeeTypeAlignment(QualType T,
  1798. LValueBaseInfo *BaseInfo = nullptr,
  1799. TBAAAccessInfo *TBAAInfo = nullptr);
  1800. Address EmitLoadOfReference(LValue RefLVal,
  1801. LValueBaseInfo *PointeeBaseInfo = nullptr,
  1802. TBAAAccessInfo *PointeeTBAAInfo = nullptr);
  1803. LValue EmitLoadOfReferenceLValue(LValue RefLVal);
  1804. LValue EmitLoadOfReferenceLValue(Address RefAddr, QualType RefTy,
  1805. AlignmentSource Source =
  1806. AlignmentSource::Type) {
  1807. LValue RefLVal = MakeAddrLValue(RefAddr, RefTy, LValueBaseInfo(Source),
  1808. CGM.getTBAAAccessInfo(RefTy));
  1809. return EmitLoadOfReferenceLValue(RefLVal);
  1810. }
  1811. Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy,
  1812. LValueBaseInfo *BaseInfo = nullptr,
  1813. TBAAAccessInfo *TBAAInfo = nullptr);
  1814. LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy);
  1815. /// CreateTempAlloca - This creates an alloca and inserts it into the entry
  1816. /// block if \p ArraySize is nullptr, otherwise inserts it at the current
  1817. /// insertion point of the builder. The caller is responsible for setting an
  1818. /// appropriate alignment on
  1819. /// the alloca.
  1820. ///
  1821. /// \p ArraySize is the number of array elements to be allocated if it
  1822. /// is not nullptr.
  1823. ///
  1824. /// LangAS::Default is the address space of pointers to local variables and
  1825. /// temporaries, as exposed in the source language. In certain
  1826. /// configurations, this is not the same as the alloca address space, and a
  1827. /// cast is needed to lift the pointer from the alloca AS into
  1828. /// LangAS::Default. This can happen when the target uses a restricted
  1829. /// address space for the stack but the source language requires
  1830. /// LangAS::Default to be a generic address space. The latter condition is
  1831. /// common for most programming languages; OpenCL is an exception in that
  1832. /// LangAS::Default is the private address space, which naturally maps
  1833. /// to the stack.
  1834. ///
  1835. /// Because the address of a temporary is often exposed to the program in
  1836. /// various ways, this function will perform the cast. The original alloca
  1837. /// instruction is returned through \p Alloca if it is not nullptr.
  1838. ///
  1839. /// The cast is not performaed in CreateTempAllocaWithoutCast. This is
  1840. /// more efficient if the caller knows that the address will not be exposed.
  1841. llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty, const Twine &Name = "tmp",
  1842. llvm::Value *ArraySize = nullptr);
  1843. Address CreateTempAlloca(llvm::Type *Ty, CharUnits align,
  1844. const Twine &Name = "tmp",
  1845. llvm::Value *ArraySize = nullptr,
  1846. Address *Alloca = nullptr);
  1847. Address CreateTempAllocaWithoutCast(llvm::Type *Ty, CharUnits align,
  1848. const Twine &Name = "tmp",
  1849. llvm::Value *ArraySize = nullptr);
  1850. /// CreateDefaultAlignedTempAlloca - This creates an alloca with the
  1851. /// default ABI alignment of the given LLVM type.
  1852. ///
  1853. /// IMPORTANT NOTE: This is *not* generally the right alignment for
  1854. /// any given AST type that happens to have been lowered to the
  1855. /// given IR type. This should only ever be used for function-local,
  1856. /// IR-driven manipulations like saving and restoring a value. Do
  1857. /// not hand this address off to arbitrary IRGen routines, and especially
  1858. /// do not pass it as an argument to a function that might expect a
  1859. /// properly ABI-aligned value.
  1860. Address CreateDefaultAlignTempAlloca(llvm::Type *Ty,
  1861. const Twine &Name = "tmp");
  1862. /// InitTempAlloca - Provide an initial value for the given alloca which
  1863. /// will be observable at all locations in the function.
  1864. ///
  1865. /// The address should be something that was returned from one of
  1866. /// the CreateTempAlloca or CreateMemTemp routines, and the
  1867. /// initializer must be valid in the entry block (i.e. it must
  1868. /// either be a constant or an argument value).
  1869. void InitTempAlloca(Address Alloca, llvm::Value *Value);
  1870. /// CreateIRTemp - Create a temporary IR object of the given type, with
  1871. /// appropriate alignment. This routine should only be used when an temporary
  1872. /// value needs to be stored into an alloca (for example, to avoid explicit
  1873. /// PHI construction), but the type is the IR type, not the type appropriate
  1874. /// for storing in memory.
  1875. ///
  1876. /// That is, this is exactly equivalent to CreateMemTemp, but calling
  1877. /// ConvertType instead of ConvertTypeForMem.
  1878. Address CreateIRTemp(QualType T, const Twine &Name = "tmp");
  1879. /// CreateMemTemp - Create a temporary memory object of the given type, with
  1880. /// appropriate alignmen and cast it to the default address space. Returns
  1881. /// the original alloca instruction by \p Alloca if it is not nullptr.
  1882. Address CreateMemTemp(QualType T, const Twine &Name = "tmp",
  1883. Address *Alloca = nullptr);
  1884. Address CreateMemTemp(QualType T, CharUnits Align, const Twine &Name = "tmp",
  1885. Address *Alloca = nullptr);
  1886. /// CreateMemTemp - Create a temporary memory object of the given type, with
  1887. /// appropriate alignmen without casting it to the default address space.
  1888. Address CreateMemTempWithoutCast(QualType T, const Twine &Name = "tmp");
  1889. Address CreateMemTempWithoutCast(QualType T, CharUnits Align,
  1890. const Twine &Name = "tmp");
  1891. /// CreateAggTemp - Create a temporary memory object for the given
  1892. /// aggregate type.
  1893. AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") {
  1894. return AggValueSlot::forAddr(CreateMemTemp(T, Name),
  1895. T.getQualifiers(),
  1896. AggValueSlot::IsNotDestructed,
  1897. AggValueSlot::DoesNotNeedGCBarriers,
  1898. AggValueSlot::IsNotAliased,
  1899. AggValueSlot::DoesNotOverlap);
  1900. }
  1901. /// Emit a cast to void* in the appropriate address space.
  1902. llvm::Value *EmitCastToVoidPtr(llvm::Value *value);
  1903. /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
  1904. /// expression and compare the result against zero, returning an Int1Ty value.
  1905. llvm::Value *EvaluateExprAsBool(const Expr *E);
  1906. /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
  1907. void EmitIgnoredExpr(const Expr *E);
  1908. /// EmitAnyExpr - Emit code to compute the specified expression which can have
  1909. /// any type. The result is returned as an RValue struct. If this is an
  1910. /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
  1911. /// the result should be returned.
  1912. ///
  1913. /// \param ignoreResult True if the resulting value isn't used.
  1914. RValue EmitAnyExpr(const Expr *E,
  1915. AggValueSlot aggSlot = AggValueSlot::ignored(),
  1916. bool ignoreResult = false);
  1917. // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
  1918. // or the value of the expression, depending on how va_list is defined.
  1919. Address EmitVAListRef(const Expr *E);
  1920. /// Emit a "reference" to a __builtin_ms_va_list; this is
  1921. /// always the value of the expression, because a __builtin_ms_va_list is a
  1922. /// pointer to a char.
  1923. Address EmitMSVAListRef(const Expr *E);
  1924. /// EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will
  1925. /// always be accessible even if no aggregate location is provided.
  1926. RValue EmitAnyExprToTemp(const Expr *E);
  1927. /// EmitAnyExprToMem - Emits the code necessary to evaluate an
  1928. /// arbitrary expression into the given memory location.
  1929. void EmitAnyExprToMem(const Expr *E, Address Location,
  1930. Qualifiers Quals, bool IsInitializer);
  1931. void EmitAnyExprToExn(const Expr *E, Address Addr);
  1932. /// EmitExprAsInit - Emits the code necessary to initialize a
  1933. /// location in memory with the given initializer.
  1934. void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue,
  1935. bool capturedByInit);
  1936. /// hasVolatileMember - returns true if aggregate type has a volatile
  1937. /// member.
  1938. bool hasVolatileMember(QualType T) {
  1939. if (const RecordType *RT = T->getAs<RecordType>()) {
  1940. const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
  1941. return RD->hasVolatileMember();
  1942. }
  1943. return false;
  1944. }
  1945. /// Determine whether a return value slot may overlap some other object.
  1946. AggValueSlot::Overlap_t getOverlapForReturnValue() {
  1947. // FIXME: Assuming no overlap here breaks guaranteed copy elision for base
  1948. // class subobjects. These cases may need to be revisited depending on the
  1949. // resolution of the relevant core issue.
  1950. return AggValueSlot::DoesNotOverlap;
  1951. }
  1952. /// Determine whether a field initialization may overlap some other object.
  1953. AggValueSlot::Overlap_t getOverlapForFieldInit(const FieldDecl *FD);
  1954. /// Determine whether a base class initialization may overlap some other
  1955. /// object.
  1956. AggValueSlot::Overlap_t getOverlapForBaseInit(const CXXRecordDecl *RD,
  1957. const CXXRecordDecl *BaseRD,
  1958. bool IsVirtual);
  1959. /// Emit an aggregate assignment.
  1960. void EmitAggregateAssign(LValue Dest, LValue Src, QualType EltTy) {
  1961. bool IsVolatile = hasVolatileMember(EltTy);
  1962. EmitAggregateCopy(Dest, Src, EltTy, AggValueSlot::MayOverlap, IsVolatile);
  1963. }
  1964. void EmitAggregateCopyCtor(LValue Dest, LValue Src,
  1965. AggValueSlot::Overlap_t MayOverlap) {
  1966. EmitAggregateCopy(Dest, Src, Src.getType(), MayOverlap);
  1967. }
  1968. /// EmitAggregateCopy - Emit an aggregate copy.
  1969. ///
  1970. /// \param isVolatile \c true iff either the source or the destination is
  1971. /// volatile.
  1972. /// \param MayOverlap Whether the tail padding of the destination might be
  1973. /// occupied by some other object. More efficient code can often be
  1974. /// generated if not.
  1975. void EmitAggregateCopy(LValue Dest, LValue Src, QualType EltTy,
  1976. AggValueSlot::Overlap_t MayOverlap,
  1977. bool isVolatile = false);
  1978. /// GetAddrOfLocalVar - Return the address of a local variable.
  1979. Address GetAddrOfLocalVar(const VarDecl *VD) {
  1980. auto it = LocalDeclMap.find(VD);
  1981. assert(it != LocalDeclMap.end() &&
  1982. "Invalid argument to GetAddrOfLocalVar(), no decl!");
  1983. return it->second;
  1984. }
  1985. /// Given an opaque value expression, return its LValue mapping if it exists,
  1986. /// otherwise create one.
  1987. LValue getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e);
  1988. /// Given an opaque value expression, return its RValue mapping if it exists,
  1989. /// otherwise create one.
  1990. RValue getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e);
  1991. /// Get the index of the current ArrayInitLoopExpr, if any.
  1992. llvm::Value *getArrayInitIndex() { return ArrayInitIndex; }
  1993. /// getAccessedFieldNo - Given an encoded value and a result number, return
  1994. /// the input field number being accessed.
  1995. static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
  1996. llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
  1997. llvm::BasicBlock *GetIndirectGotoBlock();
  1998. /// Check if \p E is a C++ "this" pointer wrapped in value-preserving casts.
  1999. static bool IsWrappedCXXThis(const Expr *E);
  2000. /// EmitNullInitialization - Generate code to set a value of the given type to
  2001. /// null, If the type contains data member pointers, they will be initialized
  2002. /// to -1 in accordance with the Itanium C++ ABI.
  2003. void EmitNullInitialization(Address DestPtr, QualType Ty);
  2004. /// Emits a call to an LLVM variable-argument intrinsic, either
  2005. /// \c llvm.va_start or \c llvm.va_end.
  2006. /// \param ArgValue A reference to the \c va_list as emitted by either
  2007. /// \c EmitVAListRef or \c EmitMSVAListRef.
  2008. /// \param IsStart If \c true, emits a call to \c llvm.va_start; otherwise,
  2009. /// calls \c llvm.va_end.
  2010. llvm::Value *EmitVAStartEnd(llvm::Value *ArgValue, bool IsStart);
  2011. /// Generate code to get an argument from the passed in pointer
  2012. /// and update it accordingly.
  2013. /// \param VE The \c VAArgExpr for which to generate code.
  2014. /// \param VAListAddr Receives a reference to the \c va_list as emitted by
  2015. /// either \c EmitVAListRef or \c EmitMSVAListRef.
  2016. /// \returns A pointer to the argument.
  2017. // FIXME: We should be able to get rid of this method and use the va_arg
  2018. // instruction in LLVM instead once it works well enough.
  2019. Address EmitVAArg(VAArgExpr *VE, Address &VAListAddr);
  2020. /// emitArrayLength - Compute the length of an array, even if it's a
  2021. /// VLA, and drill down to the base element type.
  2022. llvm::Value *emitArrayLength(const ArrayType *arrayType,
  2023. QualType &baseType,
  2024. Address &addr);
  2025. /// EmitVLASize - Capture all the sizes for the VLA expressions in
  2026. /// the given variably-modified type and store them in the VLASizeMap.
  2027. ///
  2028. /// This function can be called with a null (unreachable) insert point.
  2029. void EmitVariablyModifiedType(QualType Ty);
  2030. struct VlaSizePair {
  2031. llvm::Value *NumElts;
  2032. QualType Type;
  2033. VlaSizePair(llvm::Value *NE, QualType T) : NumElts(NE), Type(T) {}
  2034. };
  2035. /// Return the number of elements for a single dimension
  2036. /// for the given array type.
  2037. VlaSizePair getVLAElements1D(const VariableArrayType *vla);
  2038. VlaSizePair getVLAElements1D(QualType vla);
  2039. /// Returns an LLVM value that corresponds to the size,
  2040. /// in non-variably-sized elements, of a variable length array type,
  2041. /// plus that largest non-variably-sized element type. Assumes that
  2042. /// the type has already been emitted with EmitVariablyModifiedType.
  2043. VlaSizePair getVLASize(const VariableArrayType *vla);
  2044. VlaSizePair getVLASize(QualType vla);
  2045. /// LoadCXXThis - Load the value of 'this'. This function is only valid while
  2046. /// generating code for an C++ member function.
  2047. llvm::Value *LoadCXXThis() {
  2048. assert(CXXThisValue && "no 'this' value for this function");
  2049. return CXXThisValue;
  2050. }
  2051. Address LoadCXXThisAddress();
  2052. /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
  2053. /// virtual bases.
  2054. // FIXME: Every place that calls LoadCXXVTT is something
  2055. // that needs to be abstracted properly.
  2056. llvm::Value *LoadCXXVTT() {
  2057. assert(CXXStructorImplicitParamValue && "no VTT value for this function");
  2058. return CXXStructorImplicitParamValue;
  2059. }
  2060. /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
  2061. /// complete class to the given direct base.
  2062. Address
  2063. GetAddressOfDirectBaseInCompleteClass(Address Value,
  2064. const CXXRecordDecl *Derived,
  2065. const CXXRecordDecl *Base,
  2066. bool BaseIsVirtual);
  2067. static bool ShouldNullCheckClassCastValue(const CastExpr *Cast);
  2068. /// GetAddressOfBaseClass - This function will add the necessary delta to the
  2069. /// load of 'this' and returns address of the base class.
  2070. Address GetAddressOfBaseClass(Address Value,
  2071. const CXXRecordDecl *Derived,
  2072. CastExpr::path_const_iterator PathBegin,
  2073. CastExpr::path_const_iterator PathEnd,
  2074. bool NullCheckValue, SourceLocation Loc);
  2075. Address GetAddressOfDerivedClass(Address Value,
  2076. const CXXRecordDecl *Derived,
  2077. CastExpr::path_const_iterator PathBegin,
  2078. CastExpr::path_const_iterator PathEnd,
  2079. bool NullCheckValue);
  2080. /// GetVTTParameter - Return the VTT parameter that should be passed to a
  2081. /// base constructor/destructor with virtual bases.
  2082. /// FIXME: VTTs are Itanium ABI-specific, so the definition should move
  2083. /// to ItaniumCXXABI.cpp together with all the references to VTT.
  2084. llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase,
  2085. bool Delegating);
  2086. void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
  2087. CXXCtorType CtorType,
  2088. const FunctionArgList &Args,
  2089. SourceLocation Loc);
  2090. // It's important not to confuse this and the previous function. Delegating
  2091. // constructors are the C++0x feature. The constructor delegate optimization
  2092. // is used to reduce duplication in the base and complete consturctors where
  2093. // they are substantially the same.
  2094. void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
  2095. const FunctionArgList &Args);
  2096. /// Emit a call to an inheriting constructor (that is, one that invokes a
  2097. /// constructor inherited from a base class) by inlining its definition. This
  2098. /// is necessary if the ABI does not support forwarding the arguments to the
  2099. /// base class constructor (because they're variadic or similar).
  2100. void EmitInlinedInheritingCXXConstructorCall(const CXXConstructorDecl *Ctor,
  2101. CXXCtorType CtorType,
  2102. bool ForVirtualBase,
  2103. bool Delegating,
  2104. CallArgList &Args);
  2105. /// Emit a call to a constructor inherited from a base class, passing the
  2106. /// current constructor's arguments along unmodified (without even making
  2107. /// a copy).
  2108. void EmitInheritedCXXConstructorCall(const CXXConstructorDecl *D,
  2109. bool ForVirtualBase, Address This,
  2110. bool InheritedFromVBase,
  2111. const CXXInheritedCtorInitExpr *E);
  2112. void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
  2113. bool ForVirtualBase, bool Delegating,
  2114. AggValueSlot ThisAVS, const CXXConstructExpr *E);
  2115. void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
  2116. bool ForVirtualBase, bool Delegating,
  2117. Address This, CallArgList &Args,
  2118. AggValueSlot::Overlap_t Overlap,
  2119. SourceLocation Loc, bool NewPointerIsChecked);
  2120. /// Emit assumption load for all bases. Requires to be be called only on
  2121. /// most-derived class and not under construction of the object.
  2122. void EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, Address This);
  2123. /// Emit assumption that vptr load == global vtable.
  2124. void EmitVTableAssumptionLoad(const VPtr &vptr, Address This);
  2125. void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
  2126. Address This, Address Src,
  2127. const CXXConstructExpr *E);
  2128. void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
  2129. const ArrayType *ArrayTy,
  2130. Address ArrayPtr,
  2131. const CXXConstructExpr *E,
  2132. bool NewPointerIsChecked,
  2133. bool ZeroInitialization = false);
  2134. void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
  2135. llvm::Value *NumElements,
  2136. Address ArrayPtr,
  2137. const CXXConstructExpr *E,
  2138. bool NewPointerIsChecked,
  2139. bool ZeroInitialization = false);
  2140. static Destroyer destroyCXXObject;
  2141. void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
  2142. bool ForVirtualBase, bool Delegating, Address This,
  2143. QualType ThisTy);
  2144. void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
  2145. llvm::Type *ElementTy, Address NewPtr,
  2146. llvm::Value *NumElements,
  2147. llvm::Value *AllocSizeWithoutCookie);
  2148. void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
  2149. Address Ptr);
  2150. llvm::Value *EmitLifetimeStart(uint64_t Size, llvm::Value *Addr);
  2151. void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr);
  2152. llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
  2153. void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
  2154. void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
  2155. QualType DeleteTy, llvm::Value *NumElements = nullptr,
  2156. CharUnits CookieSize = CharUnits());
  2157. RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
  2158. const CallExpr *TheCallExpr, bool IsDelete);
  2159. llvm::Value *EmitCXXTypeidExpr(const CXXTypeidExpr *E);
  2160. llvm::Value *EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE);
  2161. Address EmitCXXUuidofExpr(const CXXUuidofExpr *E);
  2162. /// Situations in which we might emit a check for the suitability of a
  2163. /// pointer or glvalue.
  2164. enum TypeCheckKind {
  2165. /// Checking the operand of a load. Must be suitably sized and aligned.
  2166. TCK_Load,
  2167. /// Checking the destination of a store. Must be suitably sized and aligned.
  2168. TCK_Store,
  2169. /// Checking the bound value in a reference binding. Must be suitably sized
  2170. /// and aligned, but is not required to refer to an object (until the
  2171. /// reference is used), per core issue 453.
  2172. TCK_ReferenceBinding,
  2173. /// Checking the object expression in a non-static data member access. Must
  2174. /// be an object within its lifetime.
  2175. TCK_MemberAccess,
  2176. /// Checking the 'this' pointer for a call to a non-static member function.
  2177. /// Must be an object within its lifetime.
  2178. TCK_MemberCall,
  2179. /// Checking the 'this' pointer for a constructor call.
  2180. TCK_ConstructorCall,
  2181. /// Checking the operand of a static_cast to a derived pointer type. Must be
  2182. /// null or an object within its lifetime.
  2183. TCK_DowncastPointer,
  2184. /// Checking the operand of a static_cast to a derived reference type. Must
  2185. /// be an object within its lifetime.
  2186. TCK_DowncastReference,
  2187. /// Checking the operand of a cast to a base object. Must be suitably sized
  2188. /// and aligned.
  2189. TCK_Upcast,
  2190. /// Checking the operand of a cast to a virtual base object. Must be an
  2191. /// object within its lifetime.
  2192. TCK_UpcastToVirtualBase,
  2193. /// Checking the value assigned to a _Nonnull pointer. Must not be null.
  2194. TCK_NonnullAssign,
  2195. /// Checking the operand of a dynamic_cast or a typeid expression. Must be
  2196. /// null or an object within its lifetime.
  2197. TCK_DynamicOperation
  2198. };
  2199. /// Determine whether the pointer type check \p TCK permits null pointers.
  2200. static bool isNullPointerAllowed(TypeCheckKind TCK);
  2201. /// Determine whether the pointer type check \p TCK requires a vptr check.
  2202. static bool isVptrCheckRequired(TypeCheckKind TCK, QualType Ty);
  2203. /// Whether any type-checking sanitizers are enabled. If \c false,
  2204. /// calls to EmitTypeCheck can be skipped.
  2205. bool sanitizePerformTypeCheck() const;
  2206. /// Emit a check that \p V is the address of storage of the
  2207. /// appropriate size and alignment for an object of type \p Type
  2208. /// (or if ArraySize is provided, for an array of that bound).
  2209. void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V,
  2210. QualType Type, CharUnits Alignment = CharUnits::Zero(),
  2211. SanitizerSet SkippedChecks = SanitizerSet(),
  2212. llvm::Value *ArraySize = nullptr);
  2213. /// Emit a check that \p Base points into an array object, which
  2214. /// we can access at index \p Index. \p Accessed should be \c false if we
  2215. /// this expression is used as an lvalue, for instance in "&Arr[Idx]".
  2216. void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index,
  2217. QualType IndexType, bool Accessed);
  2218. llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
  2219. bool isInc, bool isPre);
  2220. ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
  2221. bool isInc, bool isPre);
  2222. /// Converts Location to a DebugLoc, if debug information is enabled.
  2223. llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location);
  2224. /// Get the record field index as represented in debug info.
  2225. unsigned getDebugInfoFIndex(const RecordDecl *Rec, unsigned FieldIndex);
  2226. //===--------------------------------------------------------------------===//
  2227. // Declaration Emission
  2228. //===--------------------------------------------------------------------===//
  2229. /// EmitDecl - Emit a declaration.
  2230. ///
  2231. /// This function can be called with a null (unreachable) insert point.
  2232. void EmitDecl(const Decl &D);
  2233. /// EmitVarDecl - Emit a local variable declaration.
  2234. ///
  2235. /// This function can be called with a null (unreachable) insert point.
  2236. void EmitVarDecl(const VarDecl &D);
  2237. void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue,
  2238. bool capturedByInit);
  2239. typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
  2240. llvm::Value *Address);
  2241. /// Determine whether the given initializer is trivial in the sense
  2242. /// that it requires no code to be generated.
  2243. bool isTrivialInitializer(const Expr *Init);
  2244. /// EmitAutoVarDecl - Emit an auto variable declaration.
  2245. ///
  2246. /// This function can be called with a null (unreachable) insert point.
  2247. void EmitAutoVarDecl(const VarDecl &D);
  2248. class AutoVarEmission {
  2249. friend class CodeGenFunction;
  2250. const VarDecl *Variable;
  2251. /// The address of the alloca for languages with explicit address space
  2252. /// (e.g. OpenCL) or alloca casted to generic pointer for address space
  2253. /// agnostic languages (e.g. C++). Invalid if the variable was emitted
  2254. /// as a global constant.
  2255. Address Addr;
  2256. llvm::Value *NRVOFlag;
  2257. /// True if the variable is a __block variable that is captured by an
  2258. /// escaping block.
  2259. bool IsEscapingByRef;
  2260. /// True if the variable is of aggregate type and has a constant
  2261. /// initializer.
  2262. bool IsConstantAggregate;
  2263. /// Non-null if we should use lifetime annotations.
  2264. llvm::Value *SizeForLifetimeMarkers;
  2265. /// Address with original alloca instruction. Invalid if the variable was
  2266. /// emitted as a global constant.
  2267. Address AllocaAddr;
  2268. struct Invalid {};
  2269. AutoVarEmission(Invalid)
  2270. : Variable(nullptr), Addr(Address::invalid()),
  2271. AllocaAddr(Address::invalid()) {}
  2272. AutoVarEmission(const VarDecl &variable)
  2273. : Variable(&variable), Addr(Address::invalid()), NRVOFlag(nullptr),
  2274. IsEscapingByRef(false), IsConstantAggregate(false),
  2275. SizeForLifetimeMarkers(nullptr), AllocaAddr(Address::invalid()) {}
  2276. bool wasEmittedAsGlobal() const { return !Addr.isValid(); }
  2277. public:
  2278. static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
  2279. bool useLifetimeMarkers() const {
  2280. return SizeForLifetimeMarkers != nullptr;
  2281. }
  2282. llvm::Value *getSizeForLifetimeMarkers() const {
  2283. assert(useLifetimeMarkers());
  2284. return SizeForLifetimeMarkers;
  2285. }
  2286. /// Returns the raw, allocated address, which is not necessarily
  2287. /// the address of the object itself. It is casted to default
  2288. /// address space for address space agnostic languages.
  2289. Address getAllocatedAddress() const {
  2290. return Addr;
  2291. }
  2292. /// Returns the address for the original alloca instruction.
  2293. Address getOriginalAllocatedAddress() const { return AllocaAddr; }
  2294. /// Returns the address of the object within this declaration.
  2295. /// Note that this does not chase the forwarding pointer for
  2296. /// __block decls.
  2297. Address getObjectAddress(CodeGenFunction &CGF) const {
  2298. if (!IsEscapingByRef) return Addr;
  2299. return CGF.emitBlockByrefAddress(Addr, Variable, /*forward*/ false);
  2300. }
  2301. };
  2302. AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
  2303. void EmitAutoVarInit(const AutoVarEmission &emission);
  2304. void EmitAutoVarCleanups(const AutoVarEmission &emission);
  2305. void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
  2306. QualType::DestructionKind dtorKind);
  2307. /// Emits the alloca and debug information for the size expressions for each
  2308. /// dimension of an array. It registers the association of its (1-dimensional)
  2309. /// QualTypes and size expression's debug node, so that CGDebugInfo can
  2310. /// reference this node when creating the DISubrange object to describe the
  2311. /// array types.
  2312. void EmitAndRegisterVariableArrayDimensions(CGDebugInfo *DI,
  2313. const VarDecl &D,
  2314. bool EmitDebugInfo);
  2315. void EmitStaticVarDecl(const VarDecl &D,
  2316. llvm::GlobalValue::LinkageTypes Linkage);
  2317. class ParamValue {
  2318. llvm::Value *Value;
  2319. unsigned Alignment;
  2320. ParamValue(llvm::Value *V, unsigned A) : Value(V), Alignment(A) {}
  2321. public:
  2322. static ParamValue forDirect(llvm::Value *value) {
  2323. return ParamValue(value, 0);
  2324. }
  2325. static ParamValue forIndirect(Address addr) {
  2326. assert(!addr.getAlignment().isZero());
  2327. return ParamValue(addr.getPointer(), addr.getAlignment().getQuantity());
  2328. }
  2329. bool isIndirect() const { return Alignment != 0; }
  2330. llvm::Value *getAnyValue() const { return Value; }
  2331. llvm::Value *getDirectValue() const {
  2332. assert(!isIndirect());
  2333. return Value;
  2334. }
  2335. Address getIndirectAddress() const {
  2336. assert(isIndirect());
  2337. return Address(Value, CharUnits::fromQuantity(Alignment));
  2338. }
  2339. };
  2340. /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
  2341. void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo);
  2342. /// protectFromPeepholes - Protect a value that we're intending to
  2343. /// store to the side, but which will probably be used later, from
  2344. /// aggressive peepholing optimizations that might delete it.
  2345. ///
  2346. /// Pass the result to unprotectFromPeepholes to declare that
  2347. /// protection is no longer required.
  2348. ///
  2349. /// There's no particular reason why this shouldn't apply to
  2350. /// l-values, it's just that no existing peepholes work on pointers.
  2351. PeepholeProtection protectFromPeepholes(RValue rvalue);
  2352. void unprotectFromPeepholes(PeepholeProtection protection);
  2353. void EmitAlignmentAssumptionCheck(llvm::Value *Ptr, QualType Ty,
  2354. SourceLocation Loc,
  2355. SourceLocation AssumptionLoc,
  2356. llvm::Value *Alignment,
  2357. llvm::Value *OffsetValue,
  2358. llvm::Value *TheCheck,
  2359. llvm::Instruction *Assumption);
  2360. void EmitAlignmentAssumption(llvm::Value *PtrValue, QualType Ty,
  2361. SourceLocation Loc, SourceLocation AssumptionLoc,
  2362. llvm::Value *Alignment,
  2363. llvm::Value *OffsetValue = nullptr);
  2364. void EmitAlignmentAssumption(llvm::Value *PtrValue, const Expr *E,
  2365. SourceLocation AssumptionLoc, llvm::Value *Alignment,
  2366. llvm::Value *OffsetValue = nullptr);
  2367. //===--------------------------------------------------------------------===//
  2368. // Statement Emission
  2369. //===--------------------------------------------------------------------===//
  2370. /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
  2371. void EmitStopPoint(const Stmt *S);
  2372. /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
  2373. /// this function even if there is no current insertion point.
  2374. ///
  2375. /// This function may clear the current insertion point; callers should use
  2376. /// EnsureInsertPoint if they wish to subsequently generate code without first
  2377. /// calling EmitBlock, EmitBranch, or EmitStmt.
  2378. void EmitStmt(const Stmt *S, ArrayRef<const Attr *> Attrs = None);
  2379. /// EmitSimpleStmt - Try to emit a "simple" statement which does not
  2380. /// necessarily require an insertion point or debug information; typically
  2381. /// because the statement amounts to a jump or a container of other
  2382. /// statements.
  2383. ///
  2384. /// \return True if the statement was handled.
  2385. bool EmitSimpleStmt(const Stmt *S);
  2386. Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
  2387. AggValueSlot AVS = AggValueSlot::ignored());
  2388. Address EmitCompoundStmtWithoutScope(const CompoundStmt &S,
  2389. bool GetLast = false,
  2390. AggValueSlot AVS =
  2391. AggValueSlot::ignored());
  2392. /// EmitLabel - Emit the block for the given label. It is legal to call this
  2393. /// function even if there is no current insertion point.
  2394. void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
  2395. void EmitLabelStmt(const LabelStmt &S);
  2396. void EmitAttributedStmt(const AttributedStmt &S);
  2397. void EmitGotoStmt(const GotoStmt &S);
  2398. void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
  2399. void EmitIfStmt(const IfStmt &S);
  2400. void EmitWhileStmt(const WhileStmt &S,
  2401. ArrayRef<const Attr *> Attrs = None);
  2402. void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None);
  2403. void EmitForStmt(const ForStmt &S,
  2404. ArrayRef<const Attr *> Attrs = None);
  2405. void EmitReturnStmt(const ReturnStmt &S);
  2406. void EmitDeclStmt(const DeclStmt &S);
  2407. void EmitBreakStmt(const BreakStmt &S);
  2408. void EmitContinueStmt(const ContinueStmt &S);
  2409. void EmitSwitchStmt(const SwitchStmt &S);
  2410. void EmitDefaultStmt(const DefaultStmt &S);
  2411. void EmitCaseStmt(const CaseStmt &S);
  2412. void EmitCaseStmtRange(const CaseStmt &S);
  2413. void EmitAsmStmt(const AsmStmt &S);
  2414. void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
  2415. void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
  2416. void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
  2417. void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
  2418. void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S);
  2419. void EmitCoroutineBody(const CoroutineBodyStmt &S);
  2420. void EmitCoreturnStmt(const CoreturnStmt &S);
  2421. RValue EmitCoawaitExpr(const CoawaitExpr &E,
  2422. AggValueSlot aggSlot = AggValueSlot::ignored(),
  2423. bool ignoreResult = false);
  2424. LValue EmitCoawaitLValue(const CoawaitExpr *E);
  2425. RValue EmitCoyieldExpr(const CoyieldExpr &E,
  2426. AggValueSlot aggSlot = AggValueSlot::ignored(),
  2427. bool ignoreResult = false);
  2428. LValue EmitCoyieldLValue(const CoyieldExpr *E);
  2429. RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID);
  2430. void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
  2431. void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
  2432. void EmitCXXTryStmt(const CXXTryStmt &S);
  2433. void EmitSEHTryStmt(const SEHTryStmt &S);
  2434. void EmitSEHLeaveStmt(const SEHLeaveStmt &S);
  2435. void EnterSEHTryStmt(const SEHTryStmt &S);
  2436. void ExitSEHTryStmt(const SEHTryStmt &S);
  2437. void pushSEHCleanup(CleanupKind kind,
  2438. llvm::Function *FinallyFunc);
  2439. void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter,
  2440. const Stmt *OutlinedStmt);
  2441. llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
  2442. const SEHExceptStmt &Except);
  2443. llvm::Function *GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
  2444. const SEHFinallyStmt &Finally);
  2445. void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
  2446. llvm::Value *ParentFP,
  2447. llvm::Value *EntryEBP);
  2448. llvm::Value *EmitSEHExceptionCode();
  2449. llvm::Value *EmitSEHExceptionInfo();
  2450. llvm::Value *EmitSEHAbnormalTermination();
  2451. /// Emit simple code for OpenMP directives in Simd-only mode.
  2452. void EmitSimpleOMPExecutableDirective(const OMPExecutableDirective &D);
  2453. /// Scan the outlined statement for captures from the parent function. For
  2454. /// each capture, mark the capture as escaped and emit a call to
  2455. /// llvm.localrecover. Insert the localrecover result into the LocalDeclMap.
  2456. void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt,
  2457. bool IsFilter);
  2458. /// Recovers the address of a local in a parent function. ParentVar is the
  2459. /// address of the variable used in the immediate parent function. It can
  2460. /// either be an alloca or a call to llvm.localrecover if there are nested
  2461. /// outlined functions. ParentFP is the frame pointer of the outermost parent
  2462. /// frame.
  2463. Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
  2464. Address ParentVar,
  2465. llvm::Value *ParentFP);
  2466. void EmitCXXForRangeStmt(const CXXForRangeStmt &S,
  2467. ArrayRef<const Attr *> Attrs = None);
  2468. /// Controls insertion of cancellation exit blocks in worksharing constructs.
  2469. class OMPCancelStackRAII {
  2470. CodeGenFunction &CGF;
  2471. public:
  2472. OMPCancelStackRAII(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
  2473. bool HasCancel)
  2474. : CGF(CGF) {
  2475. CGF.OMPCancelStack.enter(CGF, Kind, HasCancel);
  2476. }
  2477. ~OMPCancelStackRAII() { CGF.OMPCancelStack.exit(CGF); }
  2478. };
  2479. /// Returns calculated size of the specified type.
  2480. llvm::Value *getTypeSize(QualType Ty);
  2481. LValue InitCapturedStruct(const CapturedStmt &S);
  2482. llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K);
  2483. llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S);
  2484. Address GenerateCapturedStmtArgument(const CapturedStmt &S);
  2485. llvm::Function *GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S);
  2486. void GenerateOpenMPCapturedVars(const CapturedStmt &S,
  2487. SmallVectorImpl<llvm::Value *> &CapturedVars);
  2488. void emitOMPSimpleStore(LValue LVal, RValue RVal, QualType RValTy,
  2489. SourceLocation Loc);
  2490. /// Perform element by element copying of arrays with type \a
  2491. /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure
  2492. /// generated by \a CopyGen.
  2493. ///
  2494. /// \param DestAddr Address of the destination array.
  2495. /// \param SrcAddr Address of the source array.
  2496. /// \param OriginalType Type of destination and source arrays.
  2497. /// \param CopyGen Copying procedure that copies value of single array element
  2498. /// to another single array element.
  2499. void EmitOMPAggregateAssign(
  2500. Address DestAddr, Address SrcAddr, QualType OriginalType,
  2501. const llvm::function_ref<void(Address, Address)> CopyGen);
  2502. /// Emit proper copying of data from one variable to another.
  2503. ///
  2504. /// \param OriginalType Original type of the copied variables.
  2505. /// \param DestAddr Destination address.
  2506. /// \param SrcAddr Source address.
  2507. /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has
  2508. /// type of the base array element).
  2509. /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of
  2510. /// the base array element).
  2511. /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a
  2512. /// DestVD.
  2513. void EmitOMPCopy(QualType OriginalType,
  2514. Address DestAddr, Address SrcAddr,
  2515. const VarDecl *DestVD, const VarDecl *SrcVD,
  2516. const Expr *Copy);
  2517. /// Emit atomic update code for constructs: \a X = \a X \a BO \a E or
  2518. /// \a X = \a E \a BO \a E.
  2519. ///
  2520. /// \param X Value to be updated.
  2521. /// \param E Update value.
  2522. /// \param BO Binary operation for update operation.
  2523. /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update
  2524. /// expression, false otherwise.
  2525. /// \param AO Atomic ordering of the generated atomic instructions.
  2526. /// \param CommonGen Code generator for complex expressions that cannot be
  2527. /// expressed through atomicrmw instruction.
  2528. /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was
  2529. /// generated, <false, RValue::get(nullptr)> otherwise.
  2530. std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr(
  2531. LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
  2532. llvm::AtomicOrdering AO, SourceLocation Loc,
  2533. const llvm::function_ref<RValue(RValue)> CommonGen);
  2534. bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
  2535. OMPPrivateScope &PrivateScope);
  2536. void EmitOMPPrivateClause(const OMPExecutableDirective &D,
  2537. OMPPrivateScope &PrivateScope);
  2538. void EmitOMPUseDevicePtrClause(
  2539. const OMPClause &C, OMPPrivateScope &PrivateScope,
  2540. const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap);
  2541. /// Emit code for copyin clause in \a D directive. The next code is
  2542. /// generated at the start of outlined functions for directives:
  2543. /// \code
  2544. /// threadprivate_var1 = master_threadprivate_var1;
  2545. /// operator=(threadprivate_var2, master_threadprivate_var2);
  2546. /// ...
  2547. /// __kmpc_barrier(&loc, global_tid);
  2548. /// \endcode
  2549. ///
  2550. /// \param D OpenMP directive possibly with 'copyin' clause(s).
  2551. /// \returns true if at least one copyin variable is found, false otherwise.
  2552. bool EmitOMPCopyinClause(const OMPExecutableDirective &D);
  2553. /// Emit initial code for lastprivate variables. If some variable is
  2554. /// not also firstprivate, then the default initialization is used. Otherwise
  2555. /// initialization of this variable is performed by EmitOMPFirstprivateClause
  2556. /// method.
  2557. ///
  2558. /// \param D Directive that may have 'lastprivate' directives.
  2559. /// \param PrivateScope Private scope for capturing lastprivate variables for
  2560. /// proper codegen in internal captured statement.
  2561. ///
  2562. /// \returns true if there is at least one lastprivate variable, false
  2563. /// otherwise.
  2564. bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D,
  2565. OMPPrivateScope &PrivateScope);
  2566. /// Emit final copying of lastprivate values to original variables at
  2567. /// the end of the worksharing or simd directive.
  2568. ///
  2569. /// \param D Directive that has at least one 'lastprivate' directives.
  2570. /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if
  2571. /// it is the last iteration of the loop code in associated directive, or to
  2572. /// 'i1 false' otherwise. If this item is nullptr, no final check is required.
  2573. void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D,
  2574. bool NoFinals,
  2575. llvm::Value *IsLastIterCond = nullptr);
  2576. /// Emit initial code for linear clauses.
  2577. void EmitOMPLinearClause(const OMPLoopDirective &D,
  2578. CodeGenFunction::OMPPrivateScope &PrivateScope);
  2579. /// Emit final code for linear clauses.
  2580. /// \param CondGen Optional conditional code for final part of codegen for
  2581. /// linear clause.
  2582. void EmitOMPLinearClauseFinal(
  2583. const OMPLoopDirective &D,
  2584. const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen);
  2585. /// Emit initial code for reduction variables. Creates reduction copies
  2586. /// and initializes them with the values according to OpenMP standard.
  2587. ///
  2588. /// \param D Directive (possibly) with the 'reduction' clause.
  2589. /// \param PrivateScope Private scope for capturing reduction variables for
  2590. /// proper codegen in internal captured statement.
  2591. ///
  2592. void EmitOMPReductionClauseInit(const OMPExecutableDirective &D,
  2593. OMPPrivateScope &PrivateScope);
  2594. /// Emit final update of reduction values to original variables at
  2595. /// the end of the directive.
  2596. ///
  2597. /// \param D Directive that has at least one 'reduction' directives.
  2598. /// \param ReductionKind The kind of reduction to perform.
  2599. void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D,
  2600. const OpenMPDirectiveKind ReductionKind);
  2601. /// Emit initial code for linear variables. Creates private copies
  2602. /// and initializes them with the values according to OpenMP standard.
  2603. ///
  2604. /// \param D Directive (possibly) with the 'linear' clause.
  2605. /// \return true if at least one linear variable is found that should be
  2606. /// initialized with the value of the original variable, false otherwise.
  2607. bool EmitOMPLinearClauseInit(const OMPLoopDirective &D);
  2608. typedef const llvm::function_ref<void(CodeGenFunction & /*CGF*/,
  2609. llvm::Function * /*OutlinedFn*/,
  2610. const OMPTaskDataTy & /*Data*/)>
  2611. TaskGenTy;
  2612. void EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
  2613. const OpenMPDirectiveKind CapturedRegion,
  2614. const RegionCodeGenTy &BodyGen,
  2615. const TaskGenTy &TaskGen, OMPTaskDataTy &Data);
  2616. struct OMPTargetDataInfo {
  2617. Address BasePointersArray = Address::invalid();
  2618. Address PointersArray = Address::invalid();
  2619. Address SizesArray = Address::invalid();
  2620. unsigned NumberOfTargetItems = 0;
  2621. explicit OMPTargetDataInfo() = default;
  2622. OMPTargetDataInfo(Address BasePointersArray, Address PointersArray,
  2623. Address SizesArray, unsigned NumberOfTargetItems)
  2624. : BasePointersArray(BasePointersArray), PointersArray(PointersArray),
  2625. SizesArray(SizesArray), NumberOfTargetItems(NumberOfTargetItems) {}
  2626. };
  2627. void EmitOMPTargetTaskBasedDirective(const OMPExecutableDirective &S,
  2628. const RegionCodeGenTy &BodyGen,
  2629. OMPTargetDataInfo &InputInfo);
  2630. void EmitOMPParallelDirective(const OMPParallelDirective &S);
  2631. void EmitOMPSimdDirective(const OMPSimdDirective &S);
  2632. void EmitOMPForDirective(const OMPForDirective &S);
  2633. void EmitOMPForSimdDirective(const OMPForSimdDirective &S);
  2634. void EmitOMPSectionsDirective(const OMPSectionsDirective &S);
  2635. void EmitOMPSectionDirective(const OMPSectionDirective &S);
  2636. void EmitOMPSingleDirective(const OMPSingleDirective &S);
  2637. void EmitOMPMasterDirective(const OMPMasterDirective &S);
  2638. void EmitOMPCriticalDirective(const OMPCriticalDirective &S);
  2639. void EmitOMPParallelForDirective(const OMPParallelForDirective &S);
  2640. void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S);
  2641. void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S);
  2642. void EmitOMPTaskDirective(const OMPTaskDirective &S);
  2643. void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S);
  2644. void EmitOMPBarrierDirective(const OMPBarrierDirective &S);
  2645. void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S);
  2646. void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S);
  2647. void EmitOMPFlushDirective(const OMPFlushDirective &S);
  2648. void EmitOMPOrderedDirective(const OMPOrderedDirective &S);
  2649. void EmitOMPAtomicDirective(const OMPAtomicDirective &S);
  2650. void EmitOMPTargetDirective(const OMPTargetDirective &S);
  2651. void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S);
  2652. void EmitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &S);
  2653. void EmitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &S);
  2654. void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S);
  2655. void EmitOMPTargetParallelDirective(const OMPTargetParallelDirective &S);
  2656. void
  2657. EmitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &S);
  2658. void EmitOMPTeamsDirective(const OMPTeamsDirective &S);
  2659. void
  2660. EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S);
  2661. void EmitOMPCancelDirective(const OMPCancelDirective &S);
  2662. void EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S);
  2663. void EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S);
  2664. void EmitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &S);
  2665. void EmitOMPMasterTaskLoopDirective(const OMPMasterTaskLoopDirective &S);
  2666. void
  2667. EmitOMPMasterTaskLoopSimdDirective(const OMPMasterTaskLoopSimdDirective &S);
  2668. void EmitOMPParallelMasterTaskLoopDirective(
  2669. const OMPParallelMasterTaskLoopDirective &S);
  2670. void EmitOMPDistributeDirective(const OMPDistributeDirective &S);
  2671. void EmitOMPDistributeParallelForDirective(
  2672. const OMPDistributeParallelForDirective &S);
  2673. void EmitOMPDistributeParallelForSimdDirective(
  2674. const OMPDistributeParallelForSimdDirective &S);
  2675. void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S);
  2676. void EmitOMPTargetParallelForSimdDirective(
  2677. const OMPTargetParallelForSimdDirective &S);
  2678. void EmitOMPTargetSimdDirective(const OMPTargetSimdDirective &S);
  2679. void EmitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &S);
  2680. void
  2681. EmitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &S);
  2682. void EmitOMPTeamsDistributeParallelForSimdDirective(
  2683. const OMPTeamsDistributeParallelForSimdDirective &S);
  2684. void EmitOMPTeamsDistributeParallelForDirective(
  2685. const OMPTeamsDistributeParallelForDirective &S);
  2686. void EmitOMPTargetTeamsDirective(const OMPTargetTeamsDirective &S);
  2687. void EmitOMPTargetTeamsDistributeDirective(
  2688. const OMPTargetTeamsDistributeDirective &S);
  2689. void EmitOMPTargetTeamsDistributeParallelForDirective(
  2690. const OMPTargetTeamsDistributeParallelForDirective &S);
  2691. void EmitOMPTargetTeamsDistributeParallelForSimdDirective(
  2692. const OMPTargetTeamsDistributeParallelForSimdDirective &S);
  2693. void EmitOMPTargetTeamsDistributeSimdDirective(
  2694. const OMPTargetTeamsDistributeSimdDirective &S);
  2695. /// Emit device code for the target directive.
  2696. static void EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
  2697. StringRef ParentName,
  2698. const OMPTargetDirective &S);
  2699. static void
  2700. EmitOMPTargetParallelDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
  2701. const OMPTargetParallelDirective &S);
  2702. /// Emit device code for the target parallel for directive.
  2703. static void EmitOMPTargetParallelForDeviceFunction(
  2704. CodeGenModule &CGM, StringRef ParentName,
  2705. const OMPTargetParallelForDirective &S);
  2706. /// Emit device code for the target parallel for simd directive.
  2707. static void EmitOMPTargetParallelForSimdDeviceFunction(
  2708. CodeGenModule &CGM, StringRef ParentName,
  2709. const OMPTargetParallelForSimdDirective &S);
  2710. /// Emit device code for the target teams directive.
  2711. static void
  2712. EmitOMPTargetTeamsDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
  2713. const OMPTargetTeamsDirective &S);
  2714. /// Emit device code for the target teams distribute directive.
  2715. static void EmitOMPTargetTeamsDistributeDeviceFunction(
  2716. CodeGenModule &CGM, StringRef ParentName,
  2717. const OMPTargetTeamsDistributeDirective &S);
  2718. /// Emit device code for the target teams distribute simd directive.
  2719. static void EmitOMPTargetTeamsDistributeSimdDeviceFunction(
  2720. CodeGenModule &CGM, StringRef ParentName,
  2721. const OMPTargetTeamsDistributeSimdDirective &S);
  2722. /// Emit device code for the target simd directive.
  2723. static void EmitOMPTargetSimdDeviceFunction(CodeGenModule &CGM,
  2724. StringRef ParentName,
  2725. const OMPTargetSimdDirective &S);
  2726. /// Emit device code for the target teams distribute parallel for simd
  2727. /// directive.
  2728. static void EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
  2729. CodeGenModule &CGM, StringRef ParentName,
  2730. const OMPTargetTeamsDistributeParallelForSimdDirective &S);
  2731. static void EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
  2732. CodeGenModule &CGM, StringRef ParentName,
  2733. const OMPTargetTeamsDistributeParallelForDirective &S);
  2734. /// Emit inner loop of the worksharing/simd construct.
  2735. ///
  2736. /// \param S Directive, for which the inner loop must be emitted.
  2737. /// \param RequiresCleanup true, if directive has some associated private
  2738. /// variables.
  2739. /// \param LoopCond Bollean condition for loop continuation.
  2740. /// \param IncExpr Increment expression for loop control variable.
  2741. /// \param BodyGen Generator for the inner body of the inner loop.
  2742. /// \param PostIncGen Genrator for post-increment code (required for ordered
  2743. /// loop directvies).
  2744. void EmitOMPInnerLoop(
  2745. const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
  2746. const Expr *IncExpr,
  2747. const llvm::function_ref<void(CodeGenFunction &)> BodyGen,
  2748. const llvm::function_ref<void(CodeGenFunction &)> PostIncGen);
  2749. JumpDest getOMPCancelDestination(OpenMPDirectiveKind Kind);
  2750. /// Emit initial code for loop counters of loop-based directives.
  2751. void EmitOMPPrivateLoopCounters(const OMPLoopDirective &S,
  2752. OMPPrivateScope &LoopScope);
  2753. /// Helper for the OpenMP loop directives.
  2754. void EmitOMPLoopBody(const OMPLoopDirective &D, JumpDest LoopExit);
  2755. /// Emit code for the worksharing loop-based directive.
  2756. /// \return true, if this construct has any lastprivate clause, false -
  2757. /// otherwise.
  2758. bool EmitOMPWorksharingLoop(const OMPLoopDirective &S, Expr *EUB,
  2759. const CodeGenLoopBoundsTy &CodeGenLoopBounds,
  2760. const CodeGenDispatchBoundsTy &CGDispatchBounds);
  2761. /// Emit code for the distribute loop-based directive.
  2762. void EmitOMPDistributeLoop(const OMPLoopDirective &S,
  2763. const CodeGenLoopTy &CodeGenLoop, Expr *IncExpr);
  2764. /// Helpers for the OpenMP loop directives.
  2765. void EmitOMPSimdInit(const OMPLoopDirective &D, bool IsMonotonic = false);
  2766. void EmitOMPSimdFinal(
  2767. const OMPLoopDirective &D,
  2768. const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen);
  2769. /// Emits the lvalue for the expression with possibly captured variable.
  2770. LValue EmitOMPSharedLValue(const Expr *E);
  2771. private:
  2772. /// Helpers for blocks.
  2773. llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info);
  2774. /// struct with the values to be passed to the OpenMP loop-related functions
  2775. struct OMPLoopArguments {
  2776. /// loop lower bound
  2777. Address LB = Address::invalid();
  2778. /// loop upper bound
  2779. Address UB = Address::invalid();
  2780. /// loop stride
  2781. Address ST = Address::invalid();
  2782. /// isLastIteration argument for runtime functions
  2783. Address IL = Address::invalid();
  2784. /// Chunk value generated by sema
  2785. llvm::Value *Chunk = nullptr;
  2786. /// EnsureUpperBound
  2787. Expr *EUB = nullptr;
  2788. /// IncrementExpression
  2789. Expr *IncExpr = nullptr;
  2790. /// Loop initialization
  2791. Expr *Init = nullptr;
  2792. /// Loop exit condition
  2793. Expr *Cond = nullptr;
  2794. /// Update of LB after a whole chunk has been executed
  2795. Expr *NextLB = nullptr;
  2796. /// Update of UB after a whole chunk has been executed
  2797. Expr *NextUB = nullptr;
  2798. OMPLoopArguments() = default;
  2799. OMPLoopArguments(Address LB, Address UB, Address ST, Address IL,
  2800. llvm::Value *Chunk = nullptr, Expr *EUB = nullptr,
  2801. Expr *IncExpr = nullptr, Expr *Init = nullptr,
  2802. Expr *Cond = nullptr, Expr *NextLB = nullptr,
  2803. Expr *NextUB = nullptr)
  2804. : LB(LB), UB(UB), ST(ST), IL(IL), Chunk(Chunk), EUB(EUB),
  2805. IncExpr(IncExpr), Init(Init), Cond(Cond), NextLB(NextLB),
  2806. NextUB(NextUB) {}
  2807. };
  2808. void EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic,
  2809. const OMPLoopDirective &S, OMPPrivateScope &LoopScope,
  2810. const OMPLoopArguments &LoopArgs,
  2811. const CodeGenLoopTy &CodeGenLoop,
  2812. const CodeGenOrderedTy &CodeGenOrdered);
  2813. void EmitOMPForOuterLoop(const OpenMPScheduleTy &ScheduleKind,
  2814. bool IsMonotonic, const OMPLoopDirective &S,
  2815. OMPPrivateScope &LoopScope, bool Ordered,
  2816. const OMPLoopArguments &LoopArgs,
  2817. const CodeGenDispatchBoundsTy &CGDispatchBounds);
  2818. void EmitOMPDistributeOuterLoop(OpenMPDistScheduleClauseKind ScheduleKind,
  2819. const OMPLoopDirective &S,
  2820. OMPPrivateScope &LoopScope,
  2821. const OMPLoopArguments &LoopArgs,
  2822. const CodeGenLoopTy &CodeGenLoopContent);
  2823. /// Emit code for sections directive.
  2824. void EmitSections(const OMPExecutableDirective &S);
  2825. public:
  2826. //===--------------------------------------------------------------------===//
  2827. // LValue Expression Emission
  2828. //===--------------------------------------------------------------------===//
  2829. /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
  2830. RValue GetUndefRValue(QualType Ty);
  2831. /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
  2832. /// and issue an ErrorUnsupported style diagnostic (using the
  2833. /// provided Name).
  2834. RValue EmitUnsupportedRValue(const Expr *E,
  2835. const char *Name);
  2836. /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
  2837. /// an ErrorUnsupported style diagnostic (using the provided Name).
  2838. LValue EmitUnsupportedLValue(const Expr *E,
  2839. const char *Name);
  2840. /// EmitLValue - Emit code to compute a designator that specifies the location
  2841. /// of the expression.
  2842. ///
  2843. /// This can return one of two things: a simple address or a bitfield
  2844. /// reference. In either case, the LLVM Value* in the LValue structure is
  2845. /// guaranteed to be an LLVM pointer type.
  2846. ///
  2847. /// If this returns a bitfield reference, nothing about the pointee type of
  2848. /// the LLVM value is known: For example, it may not be a pointer to an
  2849. /// integer.
  2850. ///
  2851. /// If this returns a normal address, and if the lvalue's C type is fixed
  2852. /// size, this method guarantees that the returned pointer type will point to
  2853. /// an LLVM type of the same size of the lvalue's type. If the lvalue has a
  2854. /// variable length type, this is not possible.
  2855. ///
  2856. LValue EmitLValue(const Expr *E);
  2857. /// Same as EmitLValue but additionally we generate checking code to
  2858. /// guard against undefined behavior. This is only suitable when we know
  2859. /// that the address will be used to access the object.
  2860. LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK);
  2861. RValue convertTempToRValue(Address addr, QualType type,
  2862. SourceLocation Loc);
  2863. void EmitAtomicInit(Expr *E, LValue lvalue);
  2864. bool LValueIsSuitableForInlineAtomic(LValue Src);
  2865. RValue EmitAtomicLoad(LValue LV, SourceLocation SL,
  2866. AggValueSlot Slot = AggValueSlot::ignored());
  2867. RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc,
  2868. llvm::AtomicOrdering AO, bool IsVolatile = false,
  2869. AggValueSlot slot = AggValueSlot::ignored());
  2870. void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit);
  2871. void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO,
  2872. bool IsVolatile, bool isInit);
  2873. std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange(
  2874. LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
  2875. llvm::AtomicOrdering Success =
  2876. llvm::AtomicOrdering::SequentiallyConsistent,
  2877. llvm::AtomicOrdering Failure =
  2878. llvm::AtomicOrdering::SequentiallyConsistent,
  2879. bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored());
  2880. void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO,
  2881. const llvm::function_ref<RValue(RValue)> &UpdateOp,
  2882. bool IsVolatile);
  2883. /// EmitToMemory - Change a scalar value from its value
  2884. /// representation to its in-memory representation.
  2885. llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
  2886. /// EmitFromMemory - Change a scalar value from its memory
  2887. /// representation to its value representation.
  2888. llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
  2889. /// Check if the scalar \p Value is within the valid range for the given
  2890. /// type \p Ty.
  2891. ///
  2892. /// Returns true if a check is needed (even if the range is unknown).
  2893. bool EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
  2894. SourceLocation Loc);
  2895. /// EmitLoadOfScalar - Load a scalar value from an address, taking
  2896. /// care to appropriately convert from the memory representation to
  2897. /// the LLVM value representation.
  2898. llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
  2899. SourceLocation Loc,
  2900. AlignmentSource Source = AlignmentSource::Type,
  2901. bool isNontemporal = false) {
  2902. return EmitLoadOfScalar(Addr, Volatile, Ty, Loc, LValueBaseInfo(Source),
  2903. CGM.getTBAAAccessInfo(Ty), isNontemporal);
  2904. }
  2905. llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
  2906. SourceLocation Loc, LValueBaseInfo BaseInfo,
  2907. TBAAAccessInfo TBAAInfo,
  2908. bool isNontemporal = false);
  2909. /// EmitLoadOfScalar - Load a scalar value from an address, taking
  2910. /// care to appropriately convert from the memory representation to
  2911. /// the LLVM value representation. The l-value must be a simple
  2912. /// l-value.
  2913. llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc);
  2914. /// EmitStoreOfScalar - Store a scalar value to an address, taking
  2915. /// care to appropriately convert from the memory representation to
  2916. /// the LLVM value representation.
  2917. void EmitStoreOfScalar(llvm::Value *Value, Address Addr,
  2918. bool Volatile, QualType Ty,
  2919. AlignmentSource Source = AlignmentSource::Type,
  2920. bool isInit = false, bool isNontemporal = false) {
  2921. EmitStoreOfScalar(Value, Addr, Volatile, Ty, LValueBaseInfo(Source),
  2922. CGM.getTBAAAccessInfo(Ty), isInit, isNontemporal);
  2923. }
  2924. void EmitStoreOfScalar(llvm::Value *Value, Address Addr,
  2925. bool Volatile, QualType Ty,
  2926. LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo,
  2927. bool isInit = false, bool isNontemporal = false);
  2928. /// EmitStoreOfScalar - Store a scalar value to an address, taking
  2929. /// care to appropriately convert from the memory representation to
  2930. /// the LLVM value representation. The l-value must be a simple
  2931. /// l-value. The isInit flag indicates whether this is an initialization.
  2932. /// If so, atomic qualifiers are ignored and the store is always non-atomic.
  2933. void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false);
  2934. /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
  2935. /// this method emits the address of the lvalue, then loads the result as an
  2936. /// rvalue, returning the rvalue.
  2937. RValue EmitLoadOfLValue(LValue V, SourceLocation Loc);
  2938. RValue EmitLoadOfExtVectorElementLValue(LValue V);
  2939. RValue EmitLoadOfBitfieldLValue(LValue LV, SourceLocation Loc);
  2940. RValue EmitLoadOfGlobalRegLValue(LValue LV);
  2941. /// EmitStoreThroughLValue - Store the specified rvalue into the specified
  2942. /// lvalue, where both are guaranteed to the have the same type, and that type
  2943. /// is 'Ty'.
  2944. void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false);
  2945. void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
  2946. void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst);
  2947. /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints
  2948. /// as EmitStoreThroughLValue.
  2949. ///
  2950. /// \param Result [out] - If non-null, this will be set to a Value* for the
  2951. /// bit-field contents after the store, appropriate for use as the result of
  2952. /// an assignment to the bit-field.
  2953. void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
  2954. llvm::Value **Result=nullptr);
  2955. /// Emit an l-value for an assignment (simple or compound) of complex type.
  2956. LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
  2957. LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
  2958. LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E,
  2959. llvm::Value *&Result);
  2960. // Note: only available for agg return types
  2961. LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
  2962. LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
  2963. // Note: only available for agg return types
  2964. LValue EmitCallExprLValue(const CallExpr *E);
  2965. // Note: only available for agg return types
  2966. LValue EmitVAArgExprLValue(const VAArgExpr *E);
  2967. LValue EmitDeclRefLValue(const DeclRefExpr *E);
  2968. LValue EmitStringLiteralLValue(const StringLiteral *E);
  2969. LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
  2970. LValue EmitPredefinedLValue(const PredefinedExpr *E);
  2971. LValue EmitUnaryOpLValue(const UnaryOperator *E);
  2972. LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
  2973. bool Accessed = false);
  2974. LValue EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
  2975. bool IsLowerBound = true);
  2976. LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
  2977. LValue EmitMemberExpr(const MemberExpr *E);
  2978. LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
  2979. LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
  2980. LValue EmitInitListLValue(const InitListExpr *E);
  2981. LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E);
  2982. LValue EmitCastLValue(const CastExpr *E);
  2983. LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  2984. LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
  2985. Address EmitExtVectorElementLValue(LValue V);
  2986. RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc);
  2987. Address EmitArrayToPointerDecay(const Expr *Array,
  2988. LValueBaseInfo *BaseInfo = nullptr,
  2989. TBAAAccessInfo *TBAAInfo = nullptr);
  2990. class ConstantEmission {
  2991. llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference;
  2992. ConstantEmission(llvm::Constant *C, bool isReference)
  2993. : ValueAndIsReference(C, isReference) {}
  2994. public:
  2995. ConstantEmission() {}
  2996. static ConstantEmission forReference(llvm::Constant *C) {
  2997. return ConstantEmission(C, true);
  2998. }
  2999. static ConstantEmission forValue(llvm::Constant *C) {
  3000. return ConstantEmission(C, false);
  3001. }
  3002. explicit operator bool() const {
  3003. return ValueAndIsReference.getOpaqueValue() != nullptr;
  3004. }
  3005. bool isReference() const { return ValueAndIsReference.getInt(); }
  3006. LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const {
  3007. assert(isReference());
  3008. return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(),
  3009. refExpr->getType());
  3010. }
  3011. llvm::Constant *getValue() const {
  3012. assert(!isReference());
  3013. return ValueAndIsReference.getPointer();
  3014. }
  3015. };
  3016. ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr);
  3017. ConstantEmission tryEmitAsConstant(const MemberExpr *ME);
  3018. llvm::Value *emitScalarConstant(const ConstantEmission &Constant, Expr *E);
  3019. RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e,
  3020. AggValueSlot slot = AggValueSlot::ignored());
  3021. LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e);
  3022. llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
  3023. const ObjCIvarDecl *Ivar);
  3024. LValue EmitLValueForField(LValue Base, const FieldDecl* Field);
  3025. LValue EmitLValueForLambdaField(const FieldDecl *Field);
  3026. /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
  3027. /// if the Field is a reference, this will return the address of the reference
  3028. /// and not the address of the value stored in the reference.
  3029. LValue EmitLValueForFieldInitialization(LValue Base,
  3030. const FieldDecl* Field);
  3031. LValue EmitLValueForIvar(QualType ObjectTy,
  3032. llvm::Value* Base, const ObjCIvarDecl *Ivar,
  3033. unsigned CVRQualifiers);
  3034. LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
  3035. LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
  3036. LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
  3037. LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E);
  3038. LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
  3039. LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
  3040. LValue EmitStmtExprLValue(const StmtExpr *E);
  3041. LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
  3042. LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
  3043. void EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init);
  3044. //===--------------------------------------------------------------------===//
  3045. // Scalar Expression Emission
  3046. //===--------------------------------------------------------------------===//
  3047. /// EmitCall - Generate a call of the given function, expecting the given
  3048. /// result type, and using the given argument list which specifies both the
  3049. /// LLVM arguments and the types they were derived from.
  3050. RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee,
  3051. ReturnValueSlot ReturnValue, const CallArgList &Args,
  3052. llvm::CallBase **callOrInvoke, SourceLocation Loc);
  3053. RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee,
  3054. ReturnValueSlot ReturnValue, const CallArgList &Args,
  3055. llvm::CallBase **callOrInvoke = nullptr) {
  3056. return EmitCall(CallInfo, Callee, ReturnValue, Args, callOrInvoke,
  3057. SourceLocation());
  3058. }
  3059. RValue EmitCall(QualType FnType, const CGCallee &Callee, const CallExpr *E,
  3060. ReturnValueSlot ReturnValue, llvm::Value *Chain = nullptr);
  3061. RValue EmitCallExpr(const CallExpr *E,
  3062. ReturnValueSlot ReturnValue = ReturnValueSlot());
  3063. RValue EmitSimpleCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
  3064. CGCallee EmitCallee(const Expr *E);
  3065. void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl);
  3066. void checkTargetFeatures(SourceLocation Loc, const FunctionDecl *TargetDecl);
  3067. llvm::CallInst *EmitRuntimeCall(llvm::FunctionCallee callee,
  3068. const Twine &name = "");
  3069. llvm::CallInst *EmitRuntimeCall(llvm::FunctionCallee callee,
  3070. ArrayRef<llvm::Value *> args,
  3071. const Twine &name = "");
  3072. llvm::CallInst *EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
  3073. const Twine &name = "");
  3074. llvm::CallInst *EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
  3075. ArrayRef<llvm::Value *> args,
  3076. const Twine &name = "");
  3077. SmallVector<llvm::OperandBundleDef, 1>
  3078. getBundlesForFunclet(llvm::Value *Callee);
  3079. llvm::CallBase *EmitCallOrInvoke(llvm::FunctionCallee Callee,
  3080. ArrayRef<llvm::Value *> Args,
  3081. const Twine &Name = "");
  3082. llvm::CallBase *EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
  3083. ArrayRef<llvm::Value *> args,
  3084. const Twine &name = "");
  3085. llvm::CallBase *EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
  3086. const Twine &name = "");
  3087. void EmitNoreturnRuntimeCallOrInvoke(llvm::FunctionCallee callee,
  3088. ArrayRef<llvm::Value *> args);
  3089. CGCallee BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
  3090. NestedNameSpecifier *Qual,
  3091. llvm::Type *Ty);
  3092. CGCallee BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD,
  3093. CXXDtorType Type,
  3094. const CXXRecordDecl *RD);
  3095. // Return the copy constructor name with the prefix "__copy_constructor_"
  3096. // removed.
  3097. static std::string getNonTrivialCopyConstructorStr(QualType QT,
  3098. CharUnits Alignment,
  3099. bool IsVolatile,
  3100. ASTContext &Ctx);
  3101. // Return the destructor name with the prefix "__destructor_" removed.
  3102. static std::string getNonTrivialDestructorStr(QualType QT,
  3103. CharUnits Alignment,
  3104. bool IsVolatile,
  3105. ASTContext &Ctx);
  3106. // These functions emit calls to the special functions of non-trivial C
  3107. // structs.
  3108. void defaultInitNonTrivialCStructVar(LValue Dst);
  3109. void callCStructDefaultConstructor(LValue Dst);
  3110. void callCStructDestructor(LValue Dst);
  3111. void callCStructCopyConstructor(LValue Dst, LValue Src);
  3112. void callCStructMoveConstructor(LValue Dst, LValue Src);
  3113. void callCStructCopyAssignmentOperator(LValue Dst, LValue Src);
  3114. void callCStructMoveAssignmentOperator(LValue Dst, LValue Src);
  3115. RValue
  3116. EmitCXXMemberOrOperatorCall(const CXXMethodDecl *Method,
  3117. const CGCallee &Callee,
  3118. ReturnValueSlot ReturnValue, llvm::Value *This,
  3119. llvm::Value *ImplicitParam,
  3120. QualType ImplicitParamTy, const CallExpr *E,
  3121. CallArgList *RtlArgs);
  3122. RValue EmitCXXDestructorCall(GlobalDecl Dtor, const CGCallee &Callee,
  3123. llvm::Value *This, QualType ThisTy,
  3124. llvm::Value *ImplicitParam,
  3125. QualType ImplicitParamTy, const CallExpr *E);
  3126. RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
  3127. ReturnValueSlot ReturnValue);
  3128. RValue EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr *CE,
  3129. const CXXMethodDecl *MD,
  3130. ReturnValueSlot ReturnValue,
  3131. bool HasQualifier,
  3132. NestedNameSpecifier *Qualifier,
  3133. bool IsArrow, const Expr *Base);
  3134. // Compute the object pointer.
  3135. Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
  3136. llvm::Value *memberPtr,
  3137. const MemberPointerType *memberPtrType,
  3138. LValueBaseInfo *BaseInfo = nullptr,
  3139. TBAAAccessInfo *TBAAInfo = nullptr);
  3140. RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
  3141. ReturnValueSlot ReturnValue);
  3142. RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
  3143. const CXXMethodDecl *MD,
  3144. ReturnValueSlot ReturnValue);
  3145. RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
  3146. RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
  3147. ReturnValueSlot ReturnValue);
  3148. RValue EmitNVPTXDevicePrintfCallExpr(const CallExpr *E,
  3149. ReturnValueSlot ReturnValue);
  3150. RValue EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID,
  3151. const CallExpr *E, ReturnValueSlot ReturnValue);
  3152. RValue emitRotate(const CallExpr *E, bool IsRotateRight);
  3153. /// Emit IR for __builtin_os_log_format.
  3154. RValue emitBuiltinOSLogFormat(const CallExpr &E);
  3155. llvm::Function *generateBuiltinOSLogHelperFunction(
  3156. const analyze_os_log::OSLogBufferLayout &Layout,
  3157. CharUnits BufferAlignment);
  3158. RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
  3159. /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
  3160. /// is unhandled by the current target.
  3161. llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  3162. llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty,
  3163. const llvm::CmpInst::Predicate Fp,
  3164. const llvm::CmpInst::Predicate Ip,
  3165. const llvm::Twine &Name = "");
  3166. llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E,
  3167. llvm::Triple::ArchType Arch);
  3168. llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID,
  3169. unsigned LLVMIntrinsic,
  3170. unsigned AltLLVMIntrinsic,
  3171. const char *NameHint,
  3172. unsigned Modifier,
  3173. const CallExpr *E,
  3174. SmallVectorImpl<llvm::Value *> &Ops,
  3175. Address PtrOp0, Address PtrOp1,
  3176. llvm::Triple::ArchType Arch);
  3177. llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID,
  3178. unsigned Modifier, llvm::Type *ArgTy,
  3179. const CallExpr *E);
  3180. llvm::Value *EmitNeonCall(llvm::Function *F,
  3181. SmallVectorImpl<llvm::Value*> &O,
  3182. const char *name,
  3183. unsigned shift = 0, bool rightshift = false);
  3184. llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
  3185. llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty,
  3186. bool negateForRightShift);
  3187. llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt,
  3188. llvm::Type *Ty, bool usgn, const char *name);
  3189. llvm::Value *vectorWrapScalar16(llvm::Value *Op);
  3190. llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E,
  3191. llvm::Triple::ArchType Arch);
  3192. llvm::Value *EmitBPFBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  3193. llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops);
  3194. llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  3195. llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  3196. llvm::Value *EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  3197. llvm::Value *EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  3198. llvm::Value *EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  3199. llvm::Value *EmitWebAssemblyBuiltinExpr(unsigned BuiltinID,
  3200. const CallExpr *E);
  3201. llvm::Value *EmitHexagonBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  3202. private:
  3203. enum class MSVCIntrin;
  3204. public:
  3205. llvm::Value *EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID, const CallExpr *E);
  3206. llvm::Value *EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args);
  3207. llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
  3208. llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
  3209. llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E);
  3210. llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E);
  3211. llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E);
  3212. llvm::Value *EmitObjCCollectionLiteral(const Expr *E,
  3213. const ObjCMethodDecl *MethodWithObjects);
  3214. llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
  3215. RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
  3216. ReturnValueSlot Return = ReturnValueSlot());
  3217. /// Retrieves the default cleanup kind for an ARC cleanup.
  3218. /// Except under -fobjc-arc-eh, ARC cleanups are normal-only.
  3219. CleanupKind getARCCleanupKind() {
  3220. return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions
  3221. ? NormalAndEHCleanup : NormalCleanup;
  3222. }
  3223. // ARC primitives.
  3224. void EmitARCInitWeak(Address addr, llvm::Value *value);
  3225. void EmitARCDestroyWeak(Address addr);
  3226. llvm::Value *EmitARCLoadWeak(Address addr);
  3227. llvm::Value *EmitARCLoadWeakRetained(Address addr);
  3228. llvm::Value *EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored);
  3229. void emitARCCopyAssignWeak(QualType Ty, Address DstAddr, Address SrcAddr);
  3230. void emitARCMoveAssignWeak(QualType Ty, Address DstAddr, Address SrcAddr);
  3231. void EmitARCCopyWeak(Address dst, Address src);
  3232. void EmitARCMoveWeak(Address dst, Address src);
  3233. llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value);
  3234. llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value);
  3235. llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value,
  3236. bool resultIgnored);
  3237. llvm::Value *EmitARCStoreStrongCall(Address addr, llvm::Value *value,
  3238. bool resultIgnored);
  3239. llvm::Value *EmitARCRetain(QualType type, llvm::Value *value);
  3240. llvm::Value *EmitARCRetainNonBlock(llvm::Value *value);
  3241. llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory);
  3242. void EmitARCDestroyStrong(Address addr, ARCPreciseLifetime_t precise);
  3243. void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
  3244. llvm::Value *EmitARCAutorelease(llvm::Value *value);
  3245. llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value);
  3246. llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value);
  3247. llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value);
  3248. llvm::Value *EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value);
  3249. llvm::Value *EmitObjCAutorelease(llvm::Value *value, llvm::Type *returnType);
  3250. llvm::Value *EmitObjCRetainNonBlock(llvm::Value *value,
  3251. llvm::Type *returnType);
  3252. void EmitObjCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
  3253. std::pair<LValue,llvm::Value*>
  3254. EmitARCStoreAutoreleasing(const BinaryOperator *e);
  3255. std::pair<LValue,llvm::Value*>
  3256. EmitARCStoreStrong(const BinaryOperator *e, bool ignored);
  3257. std::pair<LValue,llvm::Value*>
  3258. EmitARCStoreUnsafeUnretained(const BinaryOperator *e, bool ignored);
  3259. llvm::Value *EmitObjCAlloc(llvm::Value *value,
  3260. llvm::Type *returnType);
  3261. llvm::Value *EmitObjCAllocWithZone(llvm::Value *value,
  3262. llvm::Type *returnType);
  3263. llvm::Value *EmitObjCAllocInit(llvm::Value *value, llvm::Type *resultType);
  3264. llvm::Value *EmitObjCThrowOperand(const Expr *expr);
  3265. llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr);
  3266. llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr);
  3267. llvm::Value *EmitARCExtendBlockObject(const Expr *expr);
  3268. llvm::Value *EmitARCReclaimReturnedObject(const Expr *e,
  3269. bool allowUnsafeClaim);
  3270. llvm::Value *EmitARCRetainScalarExpr(const Expr *expr);
  3271. llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr);
  3272. llvm::Value *EmitARCUnsafeUnretainedScalarExpr(const Expr *expr);
  3273. void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values);
  3274. static Destroyer destroyARCStrongImprecise;
  3275. static Destroyer destroyARCStrongPrecise;
  3276. static Destroyer destroyARCWeak;
  3277. static Destroyer emitARCIntrinsicUse;
  3278. static Destroyer destroyNonTrivialCStruct;
  3279. void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr);
  3280. llvm::Value *EmitObjCAutoreleasePoolPush();
  3281. llvm::Value *EmitObjCMRRAutoreleasePoolPush();
  3282. void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr);
  3283. void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr);
  3284. /// Emits a reference binding to the passed in expression.
  3285. RValue EmitReferenceBindingToExpr(const Expr *E);
  3286. //===--------------------------------------------------------------------===//
  3287. // Expression Emission
  3288. //===--------------------------------------------------------------------===//
  3289. // Expressions are broken into three classes: scalar, complex, aggregate.
  3290. /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
  3291. /// scalar type, returning the result.
  3292. llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
  3293. /// Emit a conversion from the specified type to the specified destination
  3294. /// type, both of which are LLVM scalar types.
  3295. llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
  3296. QualType DstTy, SourceLocation Loc);
  3297. /// Emit a conversion from the specified complex type to the specified
  3298. /// destination type, where the destination type is an LLVM scalar type.
  3299. llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
  3300. QualType DstTy,
  3301. SourceLocation Loc);
  3302. /// EmitAggExpr - Emit the computation of the specified expression
  3303. /// of aggregate type. The result is computed into the given slot,
  3304. /// which may be null to indicate that the value is not needed.
  3305. void EmitAggExpr(const Expr *E, AggValueSlot AS);
  3306. /// EmitAggExprToLValue - Emit the computation of the specified expression of
  3307. /// aggregate type into a temporary LValue.
  3308. LValue EmitAggExprToLValue(const Expr *E);
  3309. /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
  3310. /// make sure it survives garbage collection until this point.
  3311. void EmitExtendGCLifetime(llvm::Value *object);
  3312. /// EmitComplexExpr - Emit the computation of the specified expression of
  3313. /// complex type, returning the result.
  3314. ComplexPairTy EmitComplexExpr(const Expr *E,
  3315. bool IgnoreReal = false,
  3316. bool IgnoreImag = false);
  3317. /// EmitComplexExprIntoLValue - Emit the given expression of complex
  3318. /// type and place its result into the specified l-value.
  3319. void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit);
  3320. /// EmitStoreOfComplex - Store a complex number into the specified l-value.
  3321. void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit);
  3322. /// EmitLoadOfComplex - Load a complex number from the specified l-value.
  3323. ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc);
  3324. Address emitAddrOfRealComponent(Address complex, QualType complexType);
  3325. Address emitAddrOfImagComponent(Address complex, QualType complexType);
  3326. /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
  3327. /// global variable that has already been created for it. If the initializer
  3328. /// has a different type than GV does, this may free GV and return a different
  3329. /// one. Otherwise it just returns GV.
  3330. llvm::GlobalVariable *
  3331. AddInitializerToStaticVarDecl(const VarDecl &D,
  3332. llvm::GlobalVariable *GV);
  3333. // Emit an @llvm.invariant.start call for the given memory region.
  3334. void EmitInvariantStart(llvm::Constant *Addr, CharUnits Size);
  3335. /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
  3336. /// variable with global storage.
  3337. void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr,
  3338. bool PerformInit);
  3339. llvm::Function *createAtExitStub(const VarDecl &VD, llvm::FunctionCallee Dtor,
  3340. llvm::Constant *Addr);
  3341. /// Call atexit() with a function that passes the given argument to
  3342. /// the given function.
  3343. void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::FunctionCallee fn,
  3344. llvm::Constant *addr);
  3345. /// Call atexit() with function dtorStub.
  3346. void registerGlobalDtorWithAtExit(llvm::Constant *dtorStub);
  3347. /// Emit code in this function to perform a guarded variable
  3348. /// initialization. Guarded initializations are used when it's not
  3349. /// possible to prove that an initialization will be done exactly
  3350. /// once, e.g. with a static local variable or a static data member
  3351. /// of a class template.
  3352. void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr,
  3353. bool PerformInit);
  3354. enum class GuardKind { VariableGuard, TlsGuard };
  3355. /// Emit a branch to select whether or not to perform guarded initialization.
  3356. void EmitCXXGuardedInitBranch(llvm::Value *NeedsInit,
  3357. llvm::BasicBlock *InitBlock,
  3358. llvm::BasicBlock *NoInitBlock,
  3359. GuardKind Kind, const VarDecl *D);
  3360. /// GenerateCXXGlobalInitFunc - Generates code for initializing global
  3361. /// variables.
  3362. void
  3363. GenerateCXXGlobalInitFunc(llvm::Function *Fn,
  3364. ArrayRef<llvm::Function *> CXXThreadLocals,
  3365. ConstantAddress Guard = ConstantAddress::invalid());
  3366. /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global
  3367. /// variables.
  3368. void GenerateCXXGlobalDtorsFunc(
  3369. llvm::Function *Fn,
  3370. const std::vector<std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH,
  3371. llvm::Constant *>> &DtorsAndObjects);
  3372. void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
  3373. const VarDecl *D,
  3374. llvm::GlobalVariable *Addr,
  3375. bool PerformInit);
  3376. void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
  3377. void EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp);
  3378. void enterFullExpression(const FullExpr *E) {
  3379. if (const auto *EWC = dyn_cast<ExprWithCleanups>(E))
  3380. if (EWC->getNumObjects() == 0)
  3381. return;
  3382. enterNonTrivialFullExpression(E);
  3383. }
  3384. void enterNonTrivialFullExpression(const FullExpr *E);
  3385. void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true);
  3386. RValue EmitAtomicExpr(AtomicExpr *E);
  3387. //===--------------------------------------------------------------------===//
  3388. // Annotations Emission
  3389. //===--------------------------------------------------------------------===//
  3390. /// Emit an annotation call (intrinsic).
  3391. llvm::Value *EmitAnnotationCall(llvm::Function *AnnotationFn,
  3392. llvm::Value *AnnotatedVal,
  3393. StringRef AnnotationStr,
  3394. SourceLocation Location);
  3395. /// Emit local annotations for the local variable V, declared by D.
  3396. void EmitVarAnnotations(const VarDecl *D, llvm::Value *V);
  3397. /// Emit field annotations for the given field & value. Returns the
  3398. /// annotation result.
  3399. Address EmitFieldAnnotations(const FieldDecl *D, Address V);
  3400. //===--------------------------------------------------------------------===//
  3401. // Internal Helpers
  3402. //===--------------------------------------------------------------------===//
  3403. /// ContainsLabel - Return true if the statement contains a label in it. If
  3404. /// this statement is not executed normally, it not containing a label means
  3405. /// that we can just remove the code.
  3406. static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
  3407. /// containsBreak - Return true if the statement contains a break out of it.
  3408. /// If the statement (recursively) contains a switch or loop with a break
  3409. /// inside of it, this is fine.
  3410. static bool containsBreak(const Stmt *S);
  3411. /// Determine if the given statement might introduce a declaration into the
  3412. /// current scope, by being a (possibly-labelled) DeclStmt.
  3413. static bool mightAddDeclToScope(const Stmt *S);
  3414. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  3415. /// to a constant, or if it does but contains a label, return false. If it
  3416. /// constant folds return true and set the boolean result in Result.
  3417. bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result,
  3418. bool AllowLabels = false);
  3419. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  3420. /// to a constant, or if it does but contains a label, return false. If it
  3421. /// constant folds return true and set the folded value.
  3422. bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result,
  3423. bool AllowLabels = false);
  3424. /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
  3425. /// if statement) to the specified blocks. Based on the condition, this might
  3426. /// try to simplify the codegen of the conditional based on the branch.
  3427. /// TrueCount should be the number of times we expect the condition to
  3428. /// evaluate to true based on PGO data.
  3429. void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
  3430. llvm::BasicBlock *FalseBlock, uint64_t TrueCount);
  3431. /// Given an assignment `*LHS = RHS`, emit a test that checks if \p RHS is
  3432. /// nonnull, if \p LHS is marked _Nonnull.
  3433. void EmitNullabilityCheck(LValue LHS, llvm::Value *RHS, SourceLocation Loc);
  3434. /// An enumeration which makes it easier to specify whether or not an
  3435. /// operation is a subtraction.
  3436. enum { NotSubtraction = false, IsSubtraction = true };
  3437. /// Same as IRBuilder::CreateInBoundsGEP, but additionally emits a check to
  3438. /// detect undefined behavior when the pointer overflow sanitizer is enabled.
  3439. /// \p SignedIndices indicates whether any of the GEP indices are signed.
  3440. /// \p IsSubtraction indicates whether the expression used to form the GEP
  3441. /// is a subtraction.
  3442. llvm::Value *EmitCheckedInBoundsGEP(llvm::Value *Ptr,
  3443. ArrayRef<llvm::Value *> IdxList,
  3444. bool SignedIndices,
  3445. bool IsSubtraction,
  3446. SourceLocation Loc,
  3447. const Twine &Name = "");
  3448. /// Specifies which type of sanitizer check to apply when handling a
  3449. /// particular builtin.
  3450. enum BuiltinCheckKind {
  3451. BCK_CTZPassedZero,
  3452. BCK_CLZPassedZero,
  3453. };
  3454. /// Emits an argument for a call to a builtin. If the builtin sanitizer is
  3455. /// enabled, a runtime check specified by \p Kind is also emitted.
  3456. llvm::Value *EmitCheckedArgForBuiltin(const Expr *E, BuiltinCheckKind Kind);
  3457. /// Emit a description of a type in a format suitable for passing to
  3458. /// a runtime sanitizer handler.
  3459. llvm::Constant *EmitCheckTypeDescriptor(QualType T);
  3460. /// Convert a value into a format suitable for passing to a runtime
  3461. /// sanitizer handler.
  3462. llvm::Value *EmitCheckValue(llvm::Value *V);
  3463. /// Emit a description of a source location in a format suitable for
  3464. /// passing to a runtime sanitizer handler.
  3465. llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc);
  3466. /// Create a basic block that will either trap or call a handler function in
  3467. /// the UBSan runtime with the provided arguments, and create a conditional
  3468. /// branch to it.
  3469. void EmitCheck(ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
  3470. SanitizerHandler Check, ArrayRef<llvm::Constant *> StaticArgs,
  3471. ArrayRef<llvm::Value *> DynamicArgs);
  3472. /// Emit a slow path cross-DSO CFI check which calls __cfi_slowpath
  3473. /// if Cond if false.
  3474. void EmitCfiSlowPathCheck(SanitizerMask Kind, llvm::Value *Cond,
  3475. llvm::ConstantInt *TypeId, llvm::Value *Ptr,
  3476. ArrayRef<llvm::Constant *> StaticArgs);
  3477. /// Emit a reached-unreachable diagnostic if \p Loc is valid and runtime
  3478. /// checking is enabled. Otherwise, just emit an unreachable instruction.
  3479. void EmitUnreachable(SourceLocation Loc);
  3480. /// Create a basic block that will call the trap intrinsic, and emit a
  3481. /// conditional branch to it, for the -ftrapv checks.
  3482. void EmitTrapCheck(llvm::Value *Checked);
  3483. /// Emit a call to trap or debugtrap and attach function attribute
  3484. /// "trap-func-name" if specified.
  3485. llvm::CallInst *EmitTrapCall(llvm::Intrinsic::ID IntrID);
  3486. /// Emit a stub for the cross-DSO CFI check function.
  3487. void EmitCfiCheckStub();
  3488. /// Emit a cross-DSO CFI failure handling function.
  3489. void EmitCfiCheckFail();
  3490. /// Create a check for a function parameter that may potentially be
  3491. /// declared as non-null.
  3492. void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc,
  3493. AbstractCallee AC, unsigned ParmNum);
  3494. /// EmitCallArg - Emit a single call argument.
  3495. void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType);
  3496. /// EmitDelegateCallArg - We are performing a delegate call; that
  3497. /// is, the current function is delegating to another one. Produce
  3498. /// a r-value suitable for passing the given parameter.
  3499. void EmitDelegateCallArg(CallArgList &args, const VarDecl *param,
  3500. SourceLocation loc);
  3501. /// SetFPAccuracy - Set the minimum required accuracy of the given floating
  3502. /// point operation, expressed as the maximum relative error in ulp.
  3503. void SetFPAccuracy(llvm::Value *Val, float Accuracy);
  3504. private:
  3505. llvm::MDNode *getRangeForLoadFromType(QualType Ty);
  3506. void EmitReturnOfRValue(RValue RV, QualType Ty);
  3507. void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New);
  3508. llvm::SmallVector<std::pair<llvm::Instruction *, llvm::Value *>, 4>
  3509. DeferredReplacements;
  3510. /// Set the address of a local variable.
  3511. void setAddrOfLocalVar(const VarDecl *VD, Address Addr) {
  3512. assert(!LocalDeclMap.count(VD) && "Decl already exists in LocalDeclMap!");
  3513. LocalDeclMap.insert({VD, Addr});
  3514. }
  3515. /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
  3516. /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
  3517. ///
  3518. /// \param AI - The first function argument of the expansion.
  3519. void ExpandTypeFromArgs(QualType Ty, LValue Dst,
  3520. SmallVectorImpl<llvm::Value *>::iterator &AI);
  3521. /// ExpandTypeToArgs - Expand an CallArg \arg Arg, with the LLVM type for \arg
  3522. /// Ty, into individual arguments on the provided vector \arg IRCallArgs,
  3523. /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand.
  3524. void ExpandTypeToArgs(QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy,
  3525. SmallVectorImpl<llvm::Value *> &IRCallArgs,
  3526. unsigned &IRCallArgPos);
  3527. llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info,
  3528. const Expr *InputExpr, std::string &ConstraintStr);
  3529. llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
  3530. LValue InputValue, QualType InputType,
  3531. std::string &ConstraintStr,
  3532. SourceLocation Loc);
  3533. /// Attempts to statically evaluate the object size of E. If that
  3534. /// fails, emits code to figure the size of E out for us. This is
  3535. /// pass_object_size aware.
  3536. ///
  3537. /// If EmittedExpr is non-null, this will use that instead of re-emitting E.
  3538. llvm::Value *evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type,
  3539. llvm::IntegerType *ResType,
  3540. llvm::Value *EmittedE,
  3541. bool IsDynamic);
  3542. /// Emits the size of E, as required by __builtin_object_size. This
  3543. /// function is aware of pass_object_size parameters, and will act accordingly
  3544. /// if E is a parameter with the pass_object_size attribute.
  3545. llvm::Value *emitBuiltinObjectSize(const Expr *E, unsigned Type,
  3546. llvm::IntegerType *ResType,
  3547. llvm::Value *EmittedE,
  3548. bool IsDynamic);
  3549. void emitZeroOrPatternForAutoVarInit(QualType type, const VarDecl &D,
  3550. Address Loc);
  3551. public:
  3552. #ifndef NDEBUG
  3553. // Determine whether the given argument is an Objective-C method
  3554. // that may have type parameters in its signature.
  3555. static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
  3556. const DeclContext *dc = method->getDeclContext();
  3557. if (const ObjCInterfaceDecl *classDecl= dyn_cast<ObjCInterfaceDecl>(dc)) {
  3558. return classDecl->getTypeParamListAsWritten();
  3559. }
  3560. if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
  3561. return catDecl->getTypeParamList();
  3562. }
  3563. return false;
  3564. }
  3565. template<typename T>
  3566. static bool isObjCMethodWithTypeParams(const T *) { return false; }
  3567. #endif
  3568. enum class EvaluationOrder {
  3569. ///! No language constraints on evaluation order.
  3570. Default,
  3571. ///! Language semantics require left-to-right evaluation.
  3572. ForceLeftToRight,
  3573. ///! Language semantics require right-to-left evaluation.
  3574. ForceRightToLeft
  3575. };
  3576. /// EmitCallArgs - Emit call arguments for a function.
  3577. template <typename T>
  3578. void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo,
  3579. llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
  3580. AbstractCallee AC = AbstractCallee(),
  3581. unsigned ParamsToSkip = 0,
  3582. EvaluationOrder Order = EvaluationOrder::Default) {
  3583. SmallVector<QualType, 16> ArgTypes;
  3584. CallExpr::const_arg_iterator Arg = ArgRange.begin();
  3585. assert((ParamsToSkip == 0 || CallArgTypeInfo) &&
  3586. "Can't skip parameters if type info is not provided");
  3587. if (CallArgTypeInfo) {
  3588. #ifndef NDEBUG
  3589. bool isGenericMethod = isObjCMethodWithTypeParams(CallArgTypeInfo);
  3590. #endif
  3591. // First, use the argument types that the type info knows about
  3592. for (auto I = CallArgTypeInfo->param_type_begin() + ParamsToSkip,
  3593. E = CallArgTypeInfo->param_type_end();
  3594. I != E; ++I, ++Arg) {
  3595. assert(Arg != ArgRange.end() && "Running over edge of argument list!");
  3596. assert((isGenericMethod ||
  3597. ((*I)->isVariablyModifiedType() ||
  3598. (*I).getNonReferenceType()->isObjCRetainableType() ||
  3599. getContext()
  3600. .getCanonicalType((*I).getNonReferenceType())
  3601. .getTypePtr() ==
  3602. getContext()
  3603. .getCanonicalType((*Arg)->getType())
  3604. .getTypePtr())) &&
  3605. "type mismatch in call argument!");
  3606. ArgTypes.push_back(*I);
  3607. }
  3608. }
  3609. // Either we've emitted all the call args, or we have a call to variadic
  3610. // function.
  3611. assert((Arg == ArgRange.end() || !CallArgTypeInfo ||
  3612. CallArgTypeInfo->isVariadic()) &&
  3613. "Extra arguments in non-variadic function!");
  3614. // If we still have any arguments, emit them using the type of the argument.
  3615. for (auto *A : llvm::make_range(Arg, ArgRange.end()))
  3616. ArgTypes.push_back(CallArgTypeInfo ? getVarArgType(A) : A->getType());
  3617. EmitCallArgs(Args, ArgTypes, ArgRange, AC, ParamsToSkip, Order);
  3618. }
  3619. void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes,
  3620. llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
  3621. AbstractCallee AC = AbstractCallee(),
  3622. unsigned ParamsToSkip = 0,
  3623. EvaluationOrder Order = EvaluationOrder::Default);
  3624. /// EmitPointerWithAlignment - Given an expression with a pointer type,
  3625. /// emit the value and compute our best estimate of the alignment of the
  3626. /// pointee.
  3627. ///
  3628. /// \param BaseInfo - If non-null, this will be initialized with
  3629. /// information about the source of the alignment and the may-alias
  3630. /// attribute. Note that this function will conservatively fall back on
  3631. /// the type when it doesn't recognize the expression and may-alias will
  3632. /// be set to false.
  3633. ///
  3634. /// One reasonable way to use this information is when there's a language
  3635. /// guarantee that the pointer must be aligned to some stricter value, and
  3636. /// we're simply trying to ensure that sufficiently obvious uses of under-
  3637. /// aligned objects don't get miscompiled; for example, a placement new
  3638. /// into the address of a local variable. In such a case, it's quite
  3639. /// reasonable to just ignore the returned alignment when it isn't from an
  3640. /// explicit source.
  3641. Address EmitPointerWithAlignment(const Expr *Addr,
  3642. LValueBaseInfo *BaseInfo = nullptr,
  3643. TBAAAccessInfo *TBAAInfo = nullptr);
  3644. /// If \p E references a parameter with pass_object_size info or a constant
  3645. /// array size modifier, emit the object size divided by the size of \p EltTy.
  3646. /// Otherwise return null.
  3647. llvm::Value *LoadPassedObjectSize(const Expr *E, QualType EltTy);
  3648. void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK);
  3649. struct MultiVersionResolverOption {
  3650. llvm::Function *Function;
  3651. FunctionDecl *FD;
  3652. struct Conds {
  3653. StringRef Architecture;
  3654. llvm::SmallVector<StringRef, 8> Features;
  3655. Conds(StringRef Arch, ArrayRef<StringRef> Feats)
  3656. : Architecture(Arch), Features(Feats.begin(), Feats.end()) {}
  3657. } Conditions;
  3658. MultiVersionResolverOption(llvm::Function *F, StringRef Arch,
  3659. ArrayRef<StringRef> Feats)
  3660. : Function(F), Conditions(Arch, Feats) {}
  3661. };
  3662. // Emits the body of a multiversion function's resolver. Assumes that the
  3663. // options are already sorted in the proper order, with the 'default' option
  3664. // last (if it exists).
  3665. void EmitMultiVersionResolver(llvm::Function *Resolver,
  3666. ArrayRef<MultiVersionResolverOption> Options);
  3667. static uint64_t GetX86CpuSupportsMask(ArrayRef<StringRef> FeatureStrs);
  3668. private:
  3669. QualType getVarArgType(const Expr *Arg);
  3670. void EmitDeclMetadata();
  3671. BlockByrefHelpers *buildByrefHelpers(llvm::StructType &byrefType,
  3672. const AutoVarEmission &emission);
  3673. void AddObjCARCExceptionMetadata(llvm::Instruction *Inst);
  3674. llvm::Value *GetValueForARMHint(unsigned BuiltinID);
  3675. llvm::Value *EmitX86CpuIs(const CallExpr *E);
  3676. llvm::Value *EmitX86CpuIs(StringRef CPUStr);
  3677. llvm::Value *EmitX86CpuSupports(const CallExpr *E);
  3678. llvm::Value *EmitX86CpuSupports(ArrayRef<StringRef> FeatureStrs);
  3679. llvm::Value *EmitX86CpuSupports(uint64_t Mask);
  3680. llvm::Value *EmitX86CpuInit();
  3681. llvm::Value *FormResolverCondition(const MultiVersionResolverOption &RO);
  3682. };
  3683. inline DominatingLLVMValue::saved_type
  3684. DominatingLLVMValue::save(CodeGenFunction &CGF, llvm::Value *value) {
  3685. if (!needsSaving(value)) return saved_type(value, false);
  3686. // Otherwise, we need an alloca.
  3687. auto align = CharUnits::fromQuantity(
  3688. CGF.CGM.getDataLayout().getPrefTypeAlignment(value->getType()));
  3689. Address alloca =
  3690. CGF.CreateTempAlloca(value->getType(), align, "cond-cleanup.save");
  3691. CGF.Builder.CreateStore(value, alloca);
  3692. return saved_type(alloca.getPointer(), true);
  3693. }
  3694. inline llvm::Value *DominatingLLVMValue::restore(CodeGenFunction &CGF,
  3695. saved_type value) {
  3696. // If the value says it wasn't saved, trust that it's still dominating.
  3697. if (!value.getInt()) return value.getPointer();
  3698. // Otherwise, it should be an alloca instruction, as set up in save().
  3699. auto alloca = cast<llvm::AllocaInst>(value.getPointer());
  3700. return CGF.Builder.CreateAlignedLoad(alloca, alloca->getAlignment());
  3701. }
  3702. } // end namespace CodeGen
  3703. } // end namespace clang
  3704. #endif