CodeGenFunction.h 170 KB

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