CodeGenFunction.h 137 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290
  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 "clang/AST/CharUnits.h"
  23. #include "clang/AST/ExprCXX.h"
  24. #include "clang/AST/ExprObjC.h"
  25. #include "clang/AST/ExprOpenMP.h"
  26. #include "clang/AST/Type.h"
  27. #include "clang/Basic/ABI.h"
  28. #include "clang/Basic/CapturedStmt.h"
  29. #include "clang/Basic/OpenMPKinds.h"
  30. #include "clang/Basic/TargetInfo.h"
  31. #include "clang/Frontend/CodeGenOptions.h"
  32. #include "llvm/ADT/ArrayRef.h"
  33. #include "llvm/ADT/DenseMap.h"
  34. #include "llvm/ADT/SmallVector.h"
  35. #include "llvm/IR/ValueHandle.h"
  36. #include "llvm/Support/Debug.h"
  37. namespace llvm {
  38. class BasicBlock;
  39. class LLVMContext;
  40. class MDNode;
  41. class Module;
  42. class SwitchInst;
  43. class Twine;
  44. class Value;
  45. class CallSite;
  46. }
  47. namespace clang {
  48. class ASTContext;
  49. class BlockDecl;
  50. class CXXDestructorDecl;
  51. class CXXForRangeStmt;
  52. class CXXTryStmt;
  53. class Decl;
  54. class LabelDecl;
  55. class EnumConstantDecl;
  56. class FunctionDecl;
  57. class FunctionProtoType;
  58. class LabelStmt;
  59. class ObjCContainerDecl;
  60. class ObjCInterfaceDecl;
  61. class ObjCIvarDecl;
  62. class ObjCMethodDecl;
  63. class ObjCImplementationDecl;
  64. class ObjCPropertyImplDecl;
  65. class TargetInfo;
  66. class TargetCodeGenInfo;
  67. class VarDecl;
  68. class ObjCForCollectionStmt;
  69. class ObjCAtTryStmt;
  70. class ObjCAtThrowStmt;
  71. class ObjCAtSynchronizedStmt;
  72. class ObjCAutoreleasePoolStmt;
  73. namespace CodeGen {
  74. class CodeGenTypes;
  75. class CGFunctionInfo;
  76. class CGRecordLayout;
  77. class CGBlockInfo;
  78. class CGCXXABI;
  79. class BlockByrefHelpers;
  80. class BlockByrefInfo;
  81. class BlockFlags;
  82. class BlockFieldFlags;
  83. /// The kind of evaluation to perform on values of a particular
  84. /// type. Basically, is the code in CGExprScalar, CGExprComplex, or
  85. /// CGExprAgg?
  86. ///
  87. /// TODO: should vectors maybe be split out into their own thing?
  88. enum TypeEvaluationKind {
  89. TEK_Scalar,
  90. TEK_Complex,
  91. TEK_Aggregate
  92. };
  93. /// CodeGenFunction - This class organizes the per-function state that is used
  94. /// while generating LLVM code.
  95. class CodeGenFunction : public CodeGenTypeCache {
  96. CodeGenFunction(const CodeGenFunction &) = delete;
  97. void operator=(const CodeGenFunction &) = delete;
  98. friend class CGCXXABI;
  99. public:
  100. /// A jump destination is an abstract label, branching to which may
  101. /// require a jump out through normal cleanups.
  102. struct JumpDest {
  103. JumpDest() : Block(nullptr), ScopeDepth(), Index(0) {}
  104. JumpDest(llvm::BasicBlock *Block,
  105. EHScopeStack::stable_iterator Depth,
  106. unsigned Index)
  107. : Block(Block), ScopeDepth(Depth), Index(Index) {}
  108. bool isValid() const { return Block != nullptr; }
  109. llvm::BasicBlock *getBlock() const { return Block; }
  110. EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
  111. unsigned getDestIndex() const { return Index; }
  112. // This should be used cautiously.
  113. void setScopeDepth(EHScopeStack::stable_iterator depth) {
  114. ScopeDepth = depth;
  115. }
  116. private:
  117. llvm::BasicBlock *Block;
  118. EHScopeStack::stable_iterator ScopeDepth;
  119. unsigned Index;
  120. };
  121. CodeGenModule &CGM; // Per-module state.
  122. const TargetInfo &Target;
  123. typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
  124. LoopInfoStack LoopStack;
  125. CGBuilderTy Builder;
  126. /// \brief CGBuilder insert helper. This function is called after an
  127. /// instruction is created using Builder.
  128. void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name,
  129. llvm::BasicBlock *BB,
  130. llvm::BasicBlock::iterator InsertPt) const;
  131. /// CurFuncDecl - Holds the Decl for the current outermost
  132. /// non-closure context.
  133. const Decl *CurFuncDecl;
  134. /// CurCodeDecl - This is the inner-most code context, which includes blocks.
  135. const Decl *CurCodeDecl;
  136. const CGFunctionInfo *CurFnInfo;
  137. QualType FnRetTy;
  138. llvm::Function *CurFn;
  139. /// CurGD - The GlobalDecl for the current function being compiled.
  140. GlobalDecl CurGD;
  141. /// PrologueCleanupDepth - The cleanup depth enclosing all the
  142. /// cleanups associated with the parameters.
  143. EHScopeStack::stable_iterator PrologueCleanupDepth;
  144. /// ReturnBlock - Unified return block.
  145. JumpDest ReturnBlock;
  146. /// ReturnValue - The temporary alloca to hold the return
  147. /// value. This is invalid iff the function has no return value.
  148. Address ReturnValue;
  149. /// AllocaInsertPoint - This is an instruction in the entry block before which
  150. /// we prefer to insert allocas.
  151. llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
  152. /// \brief API for captured statement code generation.
  153. class CGCapturedStmtInfo {
  154. public:
  155. explicit CGCapturedStmtInfo(CapturedRegionKind K = CR_Default)
  156. : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {}
  157. explicit CGCapturedStmtInfo(const CapturedStmt &S,
  158. CapturedRegionKind K = CR_Default)
  159. : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {
  160. RecordDecl::field_iterator Field =
  161. S.getCapturedRecordDecl()->field_begin();
  162. for (CapturedStmt::const_capture_iterator I = S.capture_begin(),
  163. E = S.capture_end();
  164. I != E; ++I, ++Field) {
  165. if (I->capturesThis())
  166. CXXThisFieldDecl = *Field;
  167. else if (I->capturesVariable())
  168. CaptureFields[I->getCapturedVar()] = *Field;
  169. }
  170. }
  171. virtual ~CGCapturedStmtInfo();
  172. CapturedRegionKind getKind() const { return Kind; }
  173. virtual void setContextValue(llvm::Value *V) { ThisValue = V; }
  174. // \brief Retrieve the value of the context parameter.
  175. virtual llvm::Value *getContextValue() const { return ThisValue; }
  176. /// \brief Lookup the captured field decl for a variable.
  177. virtual const FieldDecl *lookup(const VarDecl *VD) const {
  178. return CaptureFields.lookup(VD);
  179. }
  180. bool isCXXThisExprCaptured() const { return getThisFieldDecl() != nullptr; }
  181. virtual FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; }
  182. static bool classof(const CGCapturedStmtInfo *) {
  183. return true;
  184. }
  185. /// \brief Emit the captured statement body.
  186. virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) {
  187. CGF.incrementProfileCounter(S);
  188. CGF.EmitStmt(S);
  189. }
  190. /// \brief Get the name of the capture helper.
  191. virtual StringRef getHelperName() const { return "__captured_stmt"; }
  192. private:
  193. /// \brief The kind of captured statement being generated.
  194. CapturedRegionKind Kind;
  195. /// \brief Keep the map between VarDecl and FieldDecl.
  196. llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields;
  197. /// \brief The base address of the captured record, passed in as the first
  198. /// argument of the parallel region function.
  199. llvm::Value *ThisValue;
  200. /// \brief Captured 'this' type.
  201. FieldDecl *CXXThisFieldDecl;
  202. };
  203. CGCapturedStmtInfo *CapturedStmtInfo;
  204. /// \brief RAII for correct setting/restoring of CapturedStmtInfo.
  205. class CGCapturedStmtRAII {
  206. private:
  207. CodeGenFunction &CGF;
  208. CGCapturedStmtInfo *PrevCapturedStmtInfo;
  209. public:
  210. CGCapturedStmtRAII(CodeGenFunction &CGF,
  211. CGCapturedStmtInfo *NewCapturedStmtInfo)
  212. : CGF(CGF), PrevCapturedStmtInfo(CGF.CapturedStmtInfo) {
  213. CGF.CapturedStmtInfo = NewCapturedStmtInfo;
  214. }
  215. ~CGCapturedStmtRAII() { CGF.CapturedStmtInfo = PrevCapturedStmtInfo; }
  216. };
  217. /// BoundsChecking - Emit run-time bounds checks. Higher values mean
  218. /// potentially higher performance penalties.
  219. unsigned char BoundsChecking;
  220. /// \brief Sanitizers enabled for this function.
  221. SanitizerSet SanOpts;
  222. /// \brief True if CodeGen currently emits code implementing sanitizer checks.
  223. bool IsSanitizerScope;
  224. /// \brief RAII object to set/unset CodeGenFunction::IsSanitizerScope.
  225. class SanitizerScope {
  226. CodeGenFunction *CGF;
  227. public:
  228. SanitizerScope(CodeGenFunction *CGF);
  229. ~SanitizerScope();
  230. };
  231. /// In C++, whether we are code generating a thunk. This controls whether we
  232. /// should emit cleanups.
  233. bool CurFuncIsThunk;
  234. /// In ARC, whether we should autorelease the return value.
  235. bool AutoreleaseResult;
  236. /// Whether we processed a Microsoft-style asm block during CodeGen. These can
  237. /// potentially set the return value.
  238. bool SawAsmBlock;
  239. /// True if the current function is an outlined SEH helper. This can be a
  240. /// finally block or filter expression.
  241. bool IsOutlinedSEHHelper;
  242. const CodeGen::CGBlockInfo *BlockInfo;
  243. llvm::Value *BlockPointer;
  244. llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
  245. FieldDecl *LambdaThisCaptureField;
  246. /// \brief A mapping from NRVO variables to the flags used to indicate
  247. /// when the NRVO has been applied to this variable.
  248. llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
  249. EHScopeStack EHStack;
  250. llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack;
  251. llvm::SmallVector<const JumpDest *, 2> SEHTryEpilogueStack;
  252. /// Header for data within LifetimeExtendedCleanupStack.
  253. struct LifetimeExtendedCleanupHeader {
  254. /// The size of the following cleanup object.
  255. unsigned Size;
  256. /// The kind of cleanup to push: a value from the CleanupKind enumeration.
  257. CleanupKind Kind;
  258. size_t getSize() const { return Size; }
  259. CleanupKind getKind() const { return Kind; }
  260. };
  261. /// i32s containing the indexes of the cleanup destinations.
  262. llvm::AllocaInst *NormalCleanupDest;
  263. unsigned NextCleanupDestIndex;
  264. /// FirstBlockInfo - The head of a singly-linked-list of block layouts.
  265. CGBlockInfo *FirstBlockInfo;
  266. /// EHResumeBlock - Unified block containing a call to llvm.eh.resume.
  267. llvm::BasicBlock *EHResumeBlock;
  268. /// The exception slot. All landing pads write the current exception pointer
  269. /// into this alloca.
  270. llvm::Value *ExceptionSlot;
  271. /// The selector slot. Under the MandatoryCleanup model, all landing pads
  272. /// write the current selector value into this alloca.
  273. llvm::AllocaInst *EHSelectorSlot;
  274. /// A stack of exception code slots. Entering an __except block pushes a slot
  275. /// on the stack and leaving pops one. The __exception_code() intrinsic loads
  276. /// a value from the top of the stack.
  277. SmallVector<Address, 1> SEHCodeSlotStack;
  278. /// Value returned by __exception_info intrinsic.
  279. llvm::Value *SEHInfo = nullptr;
  280. /// Emits a landing pad for the current EH stack.
  281. llvm::BasicBlock *EmitLandingPad();
  282. llvm::BasicBlock *getInvokeDestImpl();
  283. template <class T>
  284. typename DominatingValue<T>::saved_type saveValueInCond(T value) {
  285. return DominatingValue<T>::save(*this, value);
  286. }
  287. public:
  288. /// ObjCEHValueStack - Stack of Objective-C exception values, used for
  289. /// rethrows.
  290. SmallVector<llvm::Value*, 8> ObjCEHValueStack;
  291. /// A class controlling the emission of a finally block.
  292. class FinallyInfo {
  293. /// Where the catchall's edge through the cleanup should go.
  294. JumpDest RethrowDest;
  295. /// A function to call to enter the catch.
  296. llvm::Constant *BeginCatchFn;
  297. /// An i1 variable indicating whether or not the @finally is
  298. /// running for an exception.
  299. llvm::AllocaInst *ForEHVar;
  300. /// An i8* variable into which the exception pointer to rethrow
  301. /// has been saved.
  302. llvm::AllocaInst *SavedExnVar;
  303. public:
  304. void enter(CodeGenFunction &CGF, const Stmt *Finally,
  305. llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn,
  306. llvm::Constant *rethrowFn);
  307. void exit(CodeGenFunction &CGF);
  308. };
  309. /// Returns true inside SEH __try blocks.
  310. bool isSEHTryScope() const { return !SEHTryEpilogueStack.empty(); }
  311. /// pushFullExprCleanup - Push a cleanup to be run at the end of the
  312. /// current full-expression. Safe against the possibility that
  313. /// we're currently inside a conditionally-evaluated expression.
  314. template <class T, class... As>
  315. void pushFullExprCleanup(CleanupKind kind, As... A) {
  316. // If we're not in a conditional branch, or if none of the
  317. // arguments requires saving, then use the unconditional cleanup.
  318. if (!isInConditionalBranch())
  319. return EHStack.pushCleanup<T>(kind, A...);
  320. // Stash values in a tuple so we can guarantee the order of saves.
  321. typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
  322. SavedTuple Saved{saveValueInCond(A)...};
  323. typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
  324. EHStack.pushCleanupTuple<CleanupType>(kind, Saved);
  325. initFullExprCleanup();
  326. }
  327. /// \brief Queue a cleanup to be pushed after finishing the current
  328. /// full-expression.
  329. template <class T, class... As>
  330. void pushCleanupAfterFullExpr(CleanupKind Kind, As... A) {
  331. assert(!isInConditionalBranch() && "can't defer conditional cleanup");
  332. LifetimeExtendedCleanupHeader Header = { sizeof(T), Kind };
  333. size_t OldSize = LifetimeExtendedCleanupStack.size();
  334. LifetimeExtendedCleanupStack.resize(
  335. LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size);
  336. static_assert(sizeof(Header) % llvm::AlignOf<T>::Alignment == 0,
  337. "Cleanup will be allocated on misaligned address");
  338. char *Buffer = &LifetimeExtendedCleanupStack[OldSize];
  339. new (Buffer) LifetimeExtendedCleanupHeader(Header);
  340. new (Buffer + sizeof(Header)) T(A...);
  341. }
  342. /// Set up the last cleaup that was pushed as a conditional
  343. /// full-expression cleanup.
  344. void initFullExprCleanup();
  345. /// PushDestructorCleanup - Push a cleanup to call the
  346. /// complete-object destructor of an object of the given type at the
  347. /// given address. Does nothing if T is not a C++ class type with a
  348. /// non-trivial destructor.
  349. void PushDestructorCleanup(QualType T, Address Addr);
  350. /// PushDestructorCleanup - Push a cleanup to call the
  351. /// complete-object variant of the given destructor on the object at
  352. /// the given address.
  353. void PushDestructorCleanup(const CXXDestructorDecl *Dtor, Address Addr);
  354. /// PopCleanupBlock - Will pop the cleanup entry on the stack and
  355. /// process all branch fixups.
  356. void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
  357. /// DeactivateCleanupBlock - Deactivates the given cleanup block.
  358. /// The block cannot be reactivated. Pops it if it's the top of the
  359. /// stack.
  360. ///
  361. /// \param DominatingIP - An instruction which is known to
  362. /// dominate the current IP (if set) and which lies along
  363. /// all paths of execution between the current IP and the
  364. /// the point at which the cleanup comes into scope.
  365. void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
  366. llvm::Instruction *DominatingIP);
  367. /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
  368. /// Cannot be used to resurrect a deactivated cleanup.
  369. ///
  370. /// \param DominatingIP - An instruction which is known to
  371. /// dominate the current IP (if set) and which lies along
  372. /// all paths of execution between the current IP and the
  373. /// the point at which the cleanup comes into scope.
  374. void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
  375. llvm::Instruction *DominatingIP);
  376. /// \brief Enters a new scope for capturing cleanups, all of which
  377. /// will be executed once the scope is exited.
  378. class RunCleanupsScope {
  379. EHScopeStack::stable_iterator CleanupStackDepth;
  380. size_t LifetimeExtendedCleanupStackSize;
  381. bool OldDidCallStackSave;
  382. protected:
  383. bool PerformCleanup;
  384. private:
  385. RunCleanupsScope(const RunCleanupsScope &) = delete;
  386. void operator=(const RunCleanupsScope &) = delete;
  387. protected:
  388. CodeGenFunction& CGF;
  389. public:
  390. /// \brief Enter a new cleanup scope.
  391. explicit RunCleanupsScope(CodeGenFunction &CGF)
  392. : PerformCleanup(true), CGF(CGF)
  393. {
  394. CleanupStackDepth = CGF.EHStack.stable_begin();
  395. LifetimeExtendedCleanupStackSize =
  396. CGF.LifetimeExtendedCleanupStack.size();
  397. OldDidCallStackSave = CGF.DidCallStackSave;
  398. CGF.DidCallStackSave = false;
  399. }
  400. /// \brief Exit this cleanup scope, emitting any accumulated
  401. /// cleanups.
  402. ~RunCleanupsScope() {
  403. if (PerformCleanup) {
  404. CGF.DidCallStackSave = OldDidCallStackSave;
  405. CGF.PopCleanupBlocks(CleanupStackDepth,
  406. LifetimeExtendedCleanupStackSize);
  407. }
  408. }
  409. /// \brief Determine whether this scope requires any cleanups.
  410. bool requiresCleanups() const {
  411. return CGF.EHStack.stable_begin() != CleanupStackDepth;
  412. }
  413. /// \brief Force the emission of cleanups now, instead of waiting
  414. /// until this object is destroyed.
  415. void ForceCleanup() {
  416. assert(PerformCleanup && "Already forced cleanup");
  417. CGF.DidCallStackSave = OldDidCallStackSave;
  418. CGF.PopCleanupBlocks(CleanupStackDepth,
  419. LifetimeExtendedCleanupStackSize);
  420. PerformCleanup = false;
  421. }
  422. };
  423. class LexicalScope : public RunCleanupsScope {
  424. SourceRange Range;
  425. SmallVector<const LabelDecl*, 4> Labels;
  426. LexicalScope *ParentScope;
  427. LexicalScope(const LexicalScope &) = delete;
  428. void operator=(const LexicalScope &) = delete;
  429. public:
  430. /// \brief Enter a new cleanup scope.
  431. explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range)
  432. : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) {
  433. CGF.CurLexicalScope = this;
  434. if (CGDebugInfo *DI = CGF.getDebugInfo())
  435. DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin());
  436. }
  437. void addLabel(const LabelDecl *label) {
  438. assert(PerformCleanup && "adding label to dead scope?");
  439. Labels.push_back(label);
  440. }
  441. /// \brief Exit this cleanup scope, emitting any accumulated
  442. /// cleanups.
  443. ~LexicalScope() {
  444. if (CGDebugInfo *DI = CGF.getDebugInfo())
  445. DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
  446. // If we should perform a cleanup, force them now. Note that
  447. // this ends the cleanup scope before rescoping any labels.
  448. if (PerformCleanup) {
  449. ApplyDebugLocation DL(CGF, Range.getEnd());
  450. ForceCleanup();
  451. }
  452. }
  453. /// \brief Force the emission of cleanups now, instead of waiting
  454. /// until this object is destroyed.
  455. void ForceCleanup() {
  456. CGF.CurLexicalScope = ParentScope;
  457. RunCleanupsScope::ForceCleanup();
  458. if (!Labels.empty())
  459. rescopeLabels();
  460. }
  461. void rescopeLabels();
  462. };
  463. typedef llvm::DenseMap<const Decl *, Address> DeclMapTy;
  464. /// \brief The scope used to remap some variables as private in the OpenMP
  465. /// loop body (or other captured region emitted without outlining), and to
  466. /// restore old vars back on exit.
  467. class OMPPrivateScope : public RunCleanupsScope {
  468. DeclMapTy SavedLocals;
  469. DeclMapTy SavedPrivates;
  470. private:
  471. OMPPrivateScope(const OMPPrivateScope &) = delete;
  472. void operator=(const OMPPrivateScope &) = delete;
  473. public:
  474. /// \brief Enter a new OpenMP private scope.
  475. explicit OMPPrivateScope(CodeGenFunction &CGF) : RunCleanupsScope(CGF) {}
  476. /// \brief Registers \a LocalVD variable as a private and apply \a
  477. /// PrivateGen function for it to generate corresponding private variable.
  478. /// \a PrivateGen returns an address of the generated private variable.
  479. /// \return true if the variable is registered as private, false if it has
  480. /// been privatized already.
  481. bool
  482. addPrivate(const VarDecl *LocalVD,
  483. llvm::function_ref<Address()> PrivateGen) {
  484. assert(PerformCleanup && "adding private to dead scope");
  485. // Only save it once.
  486. if (SavedLocals.count(LocalVD)) return false;
  487. // Copy the existing local entry to SavedLocals.
  488. auto it = CGF.LocalDeclMap.find(LocalVD);
  489. if (it != CGF.LocalDeclMap.end()) {
  490. SavedLocals.insert({LocalVD, it->second});
  491. } else {
  492. SavedLocals.insert({LocalVD, Address::invalid()});
  493. }
  494. // Generate the private entry.
  495. Address Addr = PrivateGen();
  496. QualType VarTy = LocalVD->getType();
  497. if (VarTy->isReferenceType()) {
  498. Address Temp = CGF.CreateMemTemp(VarTy);
  499. CGF.Builder.CreateStore(Addr.getPointer(), Temp);
  500. Addr = Temp;
  501. }
  502. SavedPrivates.insert({LocalVD, Addr});
  503. return true;
  504. }
  505. /// \brief Privatizes local variables previously registered as private.
  506. /// Registration is separate from the actual privatization to allow
  507. /// initializers use values of the original variables, not the private one.
  508. /// This is important, for example, if the private variable is a class
  509. /// variable initialized by a constructor that references other private
  510. /// variables. But at initialization original variables must be used, not
  511. /// private copies.
  512. /// \return true if at least one variable was privatized, false otherwise.
  513. bool Privatize() {
  514. copyInto(SavedPrivates, CGF.LocalDeclMap);
  515. SavedPrivates.clear();
  516. return !SavedLocals.empty();
  517. }
  518. void ForceCleanup() {
  519. RunCleanupsScope::ForceCleanup();
  520. copyInto(SavedLocals, CGF.LocalDeclMap);
  521. SavedLocals.clear();
  522. }
  523. /// \brief Exit scope - all the mapped variables are restored.
  524. ~OMPPrivateScope() {
  525. if (PerformCleanup)
  526. ForceCleanup();
  527. }
  528. private:
  529. /// Copy all the entries in the source map over the corresponding
  530. /// entries in the destination, which must exist.
  531. static void copyInto(const DeclMapTy &src, DeclMapTy &dest) {
  532. for (auto &pair : src) {
  533. if (!pair.second.isValid()) {
  534. dest.erase(pair.first);
  535. continue;
  536. }
  537. auto it = dest.find(pair.first);
  538. if (it != dest.end()) {
  539. it->second = pair.second;
  540. } else {
  541. dest.insert(pair);
  542. }
  543. }
  544. }
  545. };
  546. /// \brief Takes the old cleanup stack size and emits the cleanup blocks
  547. /// that have been added.
  548. void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize);
  549. /// \brief Takes the old cleanup stack size and emits the cleanup blocks
  550. /// that have been added, then adds all lifetime-extended cleanups from
  551. /// the given position to the stack.
  552. void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
  553. size_t OldLifetimeExtendedStackSize);
  554. void ResolveBranchFixups(llvm::BasicBlock *Target);
  555. /// The given basic block lies in the current EH scope, but may be a
  556. /// target of a potentially scope-crossing jump; get a stable handle
  557. /// to which we can perform this jump later.
  558. JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
  559. return JumpDest(Target,
  560. EHStack.getInnermostNormalCleanup(),
  561. NextCleanupDestIndex++);
  562. }
  563. /// The given basic block lies in the current EH scope, but may be a
  564. /// target of a potentially scope-crossing jump; get a stable handle
  565. /// to which we can perform this jump later.
  566. JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) {
  567. return getJumpDestInCurrentScope(createBasicBlock(Name));
  568. }
  569. /// EmitBranchThroughCleanup - Emit a branch from the current insert
  570. /// block through the normal cleanup handling code (if any) and then
  571. /// on to \arg Dest.
  572. void EmitBranchThroughCleanup(JumpDest Dest);
  573. /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
  574. /// specified destination obviously has no cleanups to run. 'false' is always
  575. /// a conservatively correct answer for this method.
  576. bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const;
  577. /// popCatchScope - Pops the catch scope at the top of the EHScope
  578. /// stack, emitting any required code (other than the catch handlers
  579. /// themselves).
  580. void popCatchScope();
  581. llvm::BasicBlock *getEHResumeBlock(bool isCleanup);
  582. llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope);
  583. llvm::BasicBlock *getMSVCDispatchBlock(EHScopeStack::stable_iterator scope);
  584. /// An object to manage conditionally-evaluated expressions.
  585. class ConditionalEvaluation {
  586. llvm::BasicBlock *StartBB;
  587. public:
  588. ConditionalEvaluation(CodeGenFunction &CGF)
  589. : StartBB(CGF.Builder.GetInsertBlock()) {}
  590. void begin(CodeGenFunction &CGF) {
  591. assert(CGF.OutermostConditional != this);
  592. if (!CGF.OutermostConditional)
  593. CGF.OutermostConditional = this;
  594. }
  595. void end(CodeGenFunction &CGF) {
  596. assert(CGF.OutermostConditional != nullptr);
  597. if (CGF.OutermostConditional == this)
  598. CGF.OutermostConditional = nullptr;
  599. }
  600. /// Returns a block which will be executed prior to each
  601. /// evaluation of the conditional code.
  602. llvm::BasicBlock *getStartingBlock() const {
  603. return StartBB;
  604. }
  605. };
  606. /// isInConditionalBranch - Return true if we're currently emitting
  607. /// one branch or the other of a conditional expression.
  608. bool isInConditionalBranch() const { return OutermostConditional != nullptr; }
  609. void setBeforeOutermostConditional(llvm::Value *value, Address addr) {
  610. assert(isInConditionalBranch());
  611. llvm::BasicBlock *block = OutermostConditional->getStartingBlock();
  612. auto store = new llvm::StoreInst(value, addr.getPointer(), &block->back());
  613. store->setAlignment(addr.getAlignment().getQuantity());
  614. }
  615. /// An RAII object to record that we're evaluating a statement
  616. /// expression.
  617. class StmtExprEvaluation {
  618. CodeGenFunction &CGF;
  619. /// We have to save the outermost conditional: cleanups in a
  620. /// statement expression aren't conditional just because the
  621. /// StmtExpr is.
  622. ConditionalEvaluation *SavedOutermostConditional;
  623. public:
  624. StmtExprEvaluation(CodeGenFunction &CGF)
  625. : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) {
  626. CGF.OutermostConditional = nullptr;
  627. }
  628. ~StmtExprEvaluation() {
  629. CGF.OutermostConditional = SavedOutermostConditional;
  630. CGF.EnsureInsertPoint();
  631. }
  632. };
  633. /// An object which temporarily prevents a value from being
  634. /// destroyed by aggressive peephole optimizations that assume that
  635. /// all uses of a value have been realized in the IR.
  636. class PeepholeProtection {
  637. llvm::Instruction *Inst;
  638. friend class CodeGenFunction;
  639. public:
  640. PeepholeProtection() : Inst(nullptr) {}
  641. };
  642. /// A non-RAII class containing all the information about a bound
  643. /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for
  644. /// this which makes individual mappings very simple; using this
  645. /// class directly is useful when you have a variable number of
  646. /// opaque values or don't want the RAII functionality for some
  647. /// reason.
  648. class OpaqueValueMappingData {
  649. const OpaqueValueExpr *OpaqueValue;
  650. bool BoundLValue;
  651. CodeGenFunction::PeepholeProtection Protection;
  652. OpaqueValueMappingData(const OpaqueValueExpr *ov,
  653. bool boundLValue)
  654. : OpaqueValue(ov), BoundLValue(boundLValue) {}
  655. public:
  656. OpaqueValueMappingData() : OpaqueValue(nullptr) {}
  657. static bool shouldBindAsLValue(const Expr *expr) {
  658. // gl-values should be bound as l-values for obvious reasons.
  659. // Records should be bound as l-values because IR generation
  660. // always keeps them in memory. Expressions of function type
  661. // act exactly like l-values but are formally required to be
  662. // r-values in C.
  663. return expr->isGLValue() ||
  664. expr->getType()->isFunctionType() ||
  665. hasAggregateEvaluationKind(expr->getType());
  666. }
  667. static OpaqueValueMappingData bind(CodeGenFunction &CGF,
  668. const OpaqueValueExpr *ov,
  669. const Expr *e) {
  670. if (shouldBindAsLValue(ov))
  671. return bind(CGF, ov, CGF.EmitLValue(e));
  672. return bind(CGF, ov, CGF.EmitAnyExpr(e));
  673. }
  674. static OpaqueValueMappingData bind(CodeGenFunction &CGF,
  675. const OpaqueValueExpr *ov,
  676. const LValue &lv) {
  677. assert(shouldBindAsLValue(ov));
  678. CGF.OpaqueLValues.insert(std::make_pair(ov, lv));
  679. return OpaqueValueMappingData(ov, true);
  680. }
  681. static OpaqueValueMappingData bind(CodeGenFunction &CGF,
  682. const OpaqueValueExpr *ov,
  683. const RValue &rv) {
  684. assert(!shouldBindAsLValue(ov));
  685. CGF.OpaqueRValues.insert(std::make_pair(ov, rv));
  686. OpaqueValueMappingData data(ov, false);
  687. // Work around an extremely aggressive peephole optimization in
  688. // EmitScalarConversion which assumes that all other uses of a
  689. // value are extant.
  690. data.Protection = CGF.protectFromPeepholes(rv);
  691. return data;
  692. }
  693. bool isValid() const { return OpaqueValue != nullptr; }
  694. void clear() { OpaqueValue = nullptr; }
  695. void unbind(CodeGenFunction &CGF) {
  696. assert(OpaqueValue && "no data to unbind!");
  697. if (BoundLValue) {
  698. CGF.OpaqueLValues.erase(OpaqueValue);
  699. } else {
  700. CGF.OpaqueRValues.erase(OpaqueValue);
  701. CGF.unprotectFromPeepholes(Protection);
  702. }
  703. }
  704. };
  705. /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
  706. class OpaqueValueMapping {
  707. CodeGenFunction &CGF;
  708. OpaqueValueMappingData Data;
  709. public:
  710. static bool shouldBindAsLValue(const Expr *expr) {
  711. return OpaqueValueMappingData::shouldBindAsLValue(expr);
  712. }
  713. /// Build the opaque value mapping for the given conditional
  714. /// operator if it's the GNU ?: extension. This is a common
  715. /// enough pattern that the convenience operator is really
  716. /// helpful.
  717. ///
  718. OpaqueValueMapping(CodeGenFunction &CGF,
  719. const AbstractConditionalOperator *op) : CGF(CGF) {
  720. if (isa<ConditionalOperator>(op))
  721. // Leave Data empty.
  722. return;
  723. const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op);
  724. Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(),
  725. e->getCommon());
  726. }
  727. OpaqueValueMapping(CodeGenFunction &CGF,
  728. const OpaqueValueExpr *opaqueValue,
  729. LValue lvalue)
  730. : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) {
  731. }
  732. OpaqueValueMapping(CodeGenFunction &CGF,
  733. const OpaqueValueExpr *opaqueValue,
  734. RValue rvalue)
  735. : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) {
  736. }
  737. void pop() {
  738. Data.unbind(CGF);
  739. Data.clear();
  740. }
  741. ~OpaqueValueMapping() {
  742. if (Data.isValid()) Data.unbind(CGF);
  743. }
  744. };
  745. private:
  746. CGDebugInfo *DebugInfo;
  747. bool DisableDebugInfo;
  748. /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
  749. /// calling llvm.stacksave for multiple VLAs in the same scope.
  750. bool DidCallStackSave;
  751. /// IndirectBranch - The first time an indirect goto is seen we create a block
  752. /// with an indirect branch. Every time we see the address of a label taken,
  753. /// we add the label to the indirect goto. Every subsequent indirect goto is
  754. /// codegen'd as a jump to the IndirectBranch's basic block.
  755. llvm::IndirectBrInst *IndirectBranch;
  756. /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
  757. /// decls.
  758. DeclMapTy LocalDeclMap;
  759. /// Track escaped local variables with auto storage. Used during SEH
  760. /// outlining to produce a call to llvm.localescape.
  761. llvm::DenseMap<llvm::AllocaInst *, int> EscapedLocals;
  762. /// LabelMap - This keeps track of the LLVM basic block for each C label.
  763. llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap;
  764. // BreakContinueStack - This keeps track of where break and continue
  765. // statements should jump to.
  766. struct BreakContinue {
  767. BreakContinue(JumpDest Break, JumpDest Continue)
  768. : BreakBlock(Break), ContinueBlock(Continue) {}
  769. JumpDest BreakBlock;
  770. JumpDest ContinueBlock;
  771. };
  772. SmallVector<BreakContinue, 8> BreakContinueStack;
  773. CodeGenPGO PGO;
  774. /// Calculate branch weights appropriate for PGO data
  775. llvm::MDNode *createProfileWeights(uint64_t TrueCount, uint64_t FalseCount);
  776. llvm::MDNode *createProfileWeights(ArrayRef<uint64_t> Weights);
  777. llvm::MDNode *createProfileWeightsForLoop(const Stmt *Cond,
  778. uint64_t LoopCount);
  779. public:
  780. /// Increment the profiler's counter for the given statement.
  781. void incrementProfileCounter(const Stmt *S) {
  782. if (CGM.getCodeGenOpts().ProfileInstrGenerate)
  783. PGO.emitCounterIncrement(Builder, S);
  784. PGO.setCurrentStmt(S);
  785. }
  786. /// Get the profiler's count for the given statement.
  787. uint64_t getProfileCount(const Stmt *S) {
  788. Optional<uint64_t> Count = PGO.getStmtCount(S);
  789. if (!Count.hasValue())
  790. return 0;
  791. return *Count;
  792. }
  793. /// Set the profiler's current count.
  794. void setCurrentProfileCount(uint64_t Count) {
  795. PGO.setCurrentRegionCount(Count);
  796. }
  797. /// Get the profiler's current count. This is generally the count for the most
  798. /// recently incremented counter.
  799. uint64_t getCurrentProfileCount() {
  800. return PGO.getCurrentRegionCount();
  801. }
  802. private:
  803. /// SwitchInsn - This is nearest current switch instruction. It is null if
  804. /// current context is not in a switch.
  805. llvm::SwitchInst *SwitchInsn;
  806. /// The branch weights of SwitchInsn when doing instrumentation based PGO.
  807. SmallVector<uint64_t, 16> *SwitchWeights;
  808. /// CaseRangeBlock - This block holds if condition check for last case
  809. /// statement range in current switch instruction.
  810. llvm::BasicBlock *CaseRangeBlock;
  811. /// OpaqueLValues - Keeps track of the current set of opaque value
  812. /// expressions.
  813. llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
  814. llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
  815. // VLASizeMap - This keeps track of the associated size for each VLA type.
  816. // We track this by the size expression rather than the type itself because
  817. // in certain situations, like a const qualifier applied to an VLA typedef,
  818. // multiple VLA types can share the same size expression.
  819. // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
  820. // enter/leave scopes.
  821. llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
  822. /// A block containing a single 'unreachable' instruction. Created
  823. /// lazily by getUnreachableBlock().
  824. llvm::BasicBlock *UnreachableBlock;
  825. /// Counts of the number return expressions in the function.
  826. unsigned NumReturnExprs;
  827. /// Count the number of simple (constant) return expressions in the function.
  828. unsigned NumSimpleReturnExprs;
  829. /// The last regular (non-return) debug location (breakpoint) in the function.
  830. SourceLocation LastStopPoint;
  831. public:
  832. /// A scope within which we are constructing the fields of an object which
  833. /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use
  834. /// if we need to evaluate a CXXDefaultInitExpr within the evaluation.
  835. class FieldConstructionScope {
  836. public:
  837. FieldConstructionScope(CodeGenFunction &CGF, Address This)
  838. : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) {
  839. CGF.CXXDefaultInitExprThis = This;
  840. }
  841. ~FieldConstructionScope() {
  842. CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis;
  843. }
  844. private:
  845. CodeGenFunction &CGF;
  846. Address OldCXXDefaultInitExprThis;
  847. };
  848. /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this'
  849. /// is overridden to be the object under construction.
  850. class CXXDefaultInitExprScope {
  851. public:
  852. CXXDefaultInitExprScope(CodeGenFunction &CGF)
  853. : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue),
  854. OldCXXThisAlignment(CGF.CXXThisAlignment) {
  855. CGF.CXXThisValue = CGF.CXXDefaultInitExprThis.getPointer();
  856. CGF.CXXThisAlignment = CGF.CXXDefaultInitExprThis.getAlignment();
  857. }
  858. ~CXXDefaultInitExprScope() {
  859. CGF.CXXThisValue = OldCXXThisValue;
  860. CGF.CXXThisAlignment = OldCXXThisAlignment;
  861. }
  862. public:
  863. CodeGenFunction &CGF;
  864. llvm::Value *OldCXXThisValue;
  865. CharUnits OldCXXThisAlignment;
  866. };
  867. private:
  868. /// CXXThisDecl - When generating code for a C++ member function,
  869. /// this will hold the implicit 'this' declaration.
  870. ImplicitParamDecl *CXXABIThisDecl;
  871. llvm::Value *CXXABIThisValue;
  872. llvm::Value *CXXThisValue;
  873. CharUnits CXXABIThisAlignment;
  874. CharUnits CXXThisAlignment;
  875. /// The value of 'this' to use when evaluating CXXDefaultInitExprs within
  876. /// this expression.
  877. Address CXXDefaultInitExprThis = Address::invalid();
  878. /// CXXStructorImplicitParamDecl - When generating code for a constructor or
  879. /// destructor, this will hold the implicit argument (e.g. VTT).
  880. ImplicitParamDecl *CXXStructorImplicitParamDecl;
  881. llvm::Value *CXXStructorImplicitParamValue;
  882. /// OutermostConditional - Points to the outermost active
  883. /// conditional control. This is used so that we know if a
  884. /// temporary should be destroyed conditionally.
  885. ConditionalEvaluation *OutermostConditional;
  886. /// The current lexical scope.
  887. LexicalScope *CurLexicalScope;
  888. /// The current source location that should be used for exception
  889. /// handling code.
  890. SourceLocation CurEHLocation;
  891. /// BlockByrefInfos - For each __block variable, contains
  892. /// information about the layout of the variable.
  893. llvm::DenseMap<const ValueDecl *, BlockByrefInfo> BlockByrefInfos;
  894. llvm::BasicBlock *TerminateLandingPad;
  895. llvm::BasicBlock *TerminateHandler;
  896. llvm::BasicBlock *TrapBB;
  897. /// Add a kernel metadata node to the named metadata node 'opencl.kernels'.
  898. /// In the kernel metadata node, reference the kernel function and metadata
  899. /// nodes for its optional attribute qualifiers (OpenCL 1.1 6.7.2):
  900. /// - A node for the vec_type_hint(<type>) qualifier contains string
  901. /// "vec_type_hint", an undefined value of the <type> data type,
  902. /// and a Boolean that is true if the <type> is integer and signed.
  903. /// - A node for the work_group_size_hint(X,Y,Z) qualifier contains string
  904. /// "work_group_size_hint", and three 32-bit integers X, Y and Z.
  905. /// - A node for the reqd_work_group_size(X,Y,Z) qualifier contains string
  906. /// "reqd_work_group_size", and three 32-bit integers X, Y and Z.
  907. void EmitOpenCLKernelMetadata(const FunctionDecl *FD,
  908. llvm::Function *Fn);
  909. public:
  910. CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false);
  911. ~CodeGenFunction();
  912. CodeGenTypes &getTypes() const { return CGM.getTypes(); }
  913. ASTContext &getContext() const { return CGM.getContext(); }
  914. CGDebugInfo *getDebugInfo() {
  915. if (DisableDebugInfo)
  916. return nullptr;
  917. return DebugInfo;
  918. }
  919. void disableDebugInfo() { DisableDebugInfo = true; }
  920. void enableDebugInfo() { DisableDebugInfo = false; }
  921. bool shouldUseFusedARCCalls() {
  922. return CGM.getCodeGenOpts().OptimizationLevel == 0;
  923. }
  924. const LangOptions &getLangOpts() const { return CGM.getLangOpts(); }
  925. /// Returns a pointer to the function's exception object and selector slot,
  926. /// which is assigned in every landing pad.
  927. Address getExceptionSlot();
  928. Address getEHSelectorSlot();
  929. /// Returns the contents of the function's exception object and selector
  930. /// slots.
  931. llvm::Value *getExceptionFromSlot();
  932. llvm::Value *getSelectorFromSlot();
  933. Address getNormalCleanupDestSlot();
  934. llvm::BasicBlock *getUnreachableBlock() {
  935. if (!UnreachableBlock) {
  936. UnreachableBlock = createBasicBlock("unreachable");
  937. new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
  938. }
  939. return UnreachableBlock;
  940. }
  941. llvm::BasicBlock *getInvokeDest() {
  942. if (!EHStack.requiresLandingPad()) return nullptr;
  943. return getInvokeDestImpl();
  944. }
  945. bool currentFunctionUsesSEHTry() const {
  946. const auto *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
  947. return FD && FD->usesSEHTry();
  948. }
  949. const TargetInfo &getTarget() const { return Target; }
  950. llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
  951. //===--------------------------------------------------------------------===//
  952. // Cleanups
  953. //===--------------------------------------------------------------------===//
  954. typedef void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty);
  955. void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
  956. Address arrayEndPointer,
  957. QualType elementType,
  958. CharUnits elementAlignment,
  959. Destroyer *destroyer);
  960. void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
  961. llvm::Value *arrayEnd,
  962. QualType elementType,
  963. CharUnits elementAlignment,
  964. Destroyer *destroyer);
  965. void pushDestroy(QualType::DestructionKind dtorKind,
  966. Address addr, QualType type);
  967. void pushEHDestroy(QualType::DestructionKind dtorKind,
  968. Address addr, QualType type);
  969. void pushDestroy(CleanupKind kind, Address addr, QualType type,
  970. Destroyer *destroyer, bool useEHCleanupForArray);
  971. void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr,
  972. QualType type, Destroyer *destroyer,
  973. bool useEHCleanupForArray);
  974. void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
  975. llvm::Value *CompletePtr,
  976. QualType ElementType);
  977. void pushStackRestore(CleanupKind kind, Address SPMem);
  978. void emitDestroy(Address addr, QualType type, Destroyer *destroyer,
  979. bool useEHCleanupForArray);
  980. llvm::Function *generateDestroyHelper(Address addr, QualType type,
  981. Destroyer *destroyer,
  982. bool useEHCleanupForArray,
  983. const VarDecl *VD);
  984. void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
  985. QualType elementType, CharUnits elementAlign,
  986. Destroyer *destroyer,
  987. bool checkZeroLength, bool useEHCleanup);
  988. Destroyer *getDestroyer(QualType::DestructionKind destructionKind);
  989. /// Determines whether an EH cleanup is required to destroy a type
  990. /// with the given destruction kind.
  991. bool needsEHCleanup(QualType::DestructionKind kind) {
  992. switch (kind) {
  993. case QualType::DK_none:
  994. return false;
  995. case QualType::DK_cxx_destructor:
  996. case QualType::DK_objc_weak_lifetime:
  997. return getLangOpts().Exceptions;
  998. case QualType::DK_objc_strong_lifetime:
  999. return getLangOpts().Exceptions &&
  1000. CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
  1001. }
  1002. llvm_unreachable("bad destruction kind");
  1003. }
  1004. CleanupKind getCleanupKind(QualType::DestructionKind kind) {
  1005. return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup);
  1006. }
  1007. //===--------------------------------------------------------------------===//
  1008. // Objective-C
  1009. //===--------------------------------------------------------------------===//
  1010. void GenerateObjCMethod(const ObjCMethodDecl *OMD);
  1011. void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD);
  1012. /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
  1013. void GenerateObjCGetter(ObjCImplementationDecl *IMP,
  1014. const ObjCPropertyImplDecl *PID);
  1015. void generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
  1016. const ObjCPropertyImplDecl *propImpl,
  1017. const ObjCMethodDecl *GetterMothodDecl,
  1018. llvm::Constant *AtomicHelperFn);
  1019. void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
  1020. ObjCMethodDecl *MD, bool ctor);
  1021. /// GenerateObjCSetter - Synthesize an Objective-C property setter function
  1022. /// for the given property.
  1023. void GenerateObjCSetter(ObjCImplementationDecl *IMP,
  1024. const ObjCPropertyImplDecl *PID);
  1025. void generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
  1026. const ObjCPropertyImplDecl *propImpl,
  1027. llvm::Constant *AtomicHelperFn);
  1028. bool IndirectObjCSetterArg(const CGFunctionInfo &FI);
  1029. bool IvarTypeWithAggrGCObjects(QualType Ty);
  1030. //===--------------------------------------------------------------------===//
  1031. // Block Bits
  1032. //===--------------------------------------------------------------------===//
  1033. llvm::Value *EmitBlockLiteral(const BlockExpr *);
  1034. llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info);
  1035. static void destroyBlockInfos(CGBlockInfo *info);
  1036. llvm::Constant *BuildDescriptorBlockDecl(const BlockExpr *,
  1037. const CGBlockInfo &Info,
  1038. llvm::StructType *,
  1039. llvm::Constant *BlockVarLayout);
  1040. llvm::Function *GenerateBlockFunction(GlobalDecl GD,
  1041. const CGBlockInfo &Info,
  1042. const DeclMapTy &ldm,
  1043. bool IsLambdaConversionToBlock);
  1044. llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
  1045. llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
  1046. llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction(
  1047. const ObjCPropertyImplDecl *PID);
  1048. llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction(
  1049. const ObjCPropertyImplDecl *PID);
  1050. llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty);
  1051. void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags);
  1052. class AutoVarEmission;
  1053. void emitByrefStructureInit(const AutoVarEmission &emission);
  1054. void enterByrefCleanup(const AutoVarEmission &emission);
  1055. void setBlockContextParameter(const ImplicitParamDecl *D, unsigned argNum,
  1056. llvm::Value *ptr);
  1057. Address LoadBlockStruct();
  1058. void AllocateBlockCXXThisPointer(const CXXThisExpr *E);
  1059. void AllocateBlockDecl(const DeclRefExpr *E);
  1060. Address GetAddrOfBlockDecl(const VarDecl *var, bool ByRef);
  1061. /// BuildBlockByrefAddress - Computes the location of the
  1062. /// data in a variable which is declared as __block.
  1063. Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V,
  1064. bool followForward = true);
  1065. Address emitBlockByrefAddress(Address baseAddr,
  1066. const BlockByrefInfo &info,
  1067. bool followForward,
  1068. const llvm::Twine &name);
  1069. const BlockByrefInfo &getBlockByrefInfo(const VarDecl *var);
  1070. void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
  1071. const CGFunctionInfo &FnInfo);
  1072. /// \brief Emit code for the start of a function.
  1073. /// \param Loc The location to be associated with the function.
  1074. /// \param StartLoc The location of the function body.
  1075. void StartFunction(GlobalDecl GD,
  1076. QualType RetTy,
  1077. llvm::Function *Fn,
  1078. const CGFunctionInfo &FnInfo,
  1079. const FunctionArgList &Args,
  1080. SourceLocation Loc = SourceLocation(),
  1081. SourceLocation StartLoc = SourceLocation());
  1082. void EmitConstructorBody(FunctionArgList &Args);
  1083. void EmitDestructorBody(FunctionArgList &Args);
  1084. void emitImplicitAssignmentOperatorBody(FunctionArgList &Args);
  1085. void EmitFunctionBody(FunctionArgList &Args, const Stmt *Body);
  1086. void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S);
  1087. void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator,
  1088. CallArgList &CallArgs);
  1089. void EmitLambdaToBlockPointerBody(FunctionArgList &Args);
  1090. void EmitLambdaBlockInvokeBody();
  1091. void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD);
  1092. void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD);
  1093. void EmitAsanPrologueOrEpilogue(bool Prologue);
  1094. /// \brief Emit the unified return block, trying to avoid its emission when
  1095. /// possible.
  1096. /// \return The debug location of the user written return statement if the
  1097. /// return block is is avoided.
  1098. llvm::DebugLoc EmitReturnBlock();
  1099. /// FinishFunction - Complete IR generation of the current function. It is
  1100. /// legal to call this function even if there is no current insertion point.
  1101. void FinishFunction(SourceLocation EndLoc=SourceLocation());
  1102. void StartThunk(llvm::Function *Fn, GlobalDecl GD,
  1103. const CGFunctionInfo &FnInfo);
  1104. void EmitCallAndReturnForThunk(llvm::Value *Callee, const ThunkInfo *Thunk);
  1105. void FinishThunk();
  1106. /// Emit a musttail call for a thunk with a potentially adjusted this pointer.
  1107. void EmitMustTailThunk(const CXXMethodDecl *MD, llvm::Value *AdjustedThisPtr,
  1108. llvm::Value *Callee);
  1109. /// Generate a thunk for the given method.
  1110. void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
  1111. GlobalDecl GD, const ThunkInfo &Thunk);
  1112. llvm::Function *GenerateVarArgsThunk(llvm::Function *Fn,
  1113. const CGFunctionInfo &FnInfo,
  1114. GlobalDecl GD, const ThunkInfo &Thunk);
  1115. void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
  1116. FunctionArgList &Args);
  1117. void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init,
  1118. ArrayRef<VarDecl *> ArrayIndexes);
  1119. /// InitializeVTablePointer - Initialize the vtable pointer of the given
  1120. /// subobject.
  1121. ///
  1122. void InitializeVTablePointer(BaseSubobject Base,
  1123. const CXXRecordDecl *NearestVBase,
  1124. CharUnits OffsetFromNearestVBase,
  1125. const CXXRecordDecl *VTableClass);
  1126. typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
  1127. void InitializeVTablePointers(BaseSubobject Base,
  1128. const CXXRecordDecl *NearestVBase,
  1129. CharUnits OffsetFromNearestVBase,
  1130. bool BaseIsNonVirtualPrimaryBase,
  1131. const CXXRecordDecl *VTableClass,
  1132. VisitedVirtualBasesSetTy& VBases);
  1133. void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
  1134. /// GetVTablePtr - Return the Value of the vtable pointer member pointed
  1135. /// to by This.
  1136. llvm::Value *GetVTablePtr(Address This, llvm::Type *Ty);
  1137. enum CFITypeCheckKind {
  1138. CFITCK_VCall,
  1139. CFITCK_NVCall,
  1140. CFITCK_DerivedCast,
  1141. CFITCK_UnrelatedCast,
  1142. };
  1143. /// \brief Derived is the presumed address of an object of type T after a
  1144. /// cast. If T is a polymorphic class type, emit a check that the virtual
  1145. /// table for Derived belongs to a class derived from T.
  1146. void EmitVTablePtrCheckForCast(QualType T, llvm::Value *Derived,
  1147. bool MayBeNull, CFITypeCheckKind TCK,
  1148. SourceLocation Loc);
  1149. /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable.
  1150. /// If vptr CFI is enabled, emit a check that VTable is valid.
  1151. void EmitVTablePtrCheckForCall(const CXXMethodDecl *MD, llvm::Value *VTable,
  1152. CFITypeCheckKind TCK, SourceLocation Loc);
  1153. /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for
  1154. /// RD using llvm.bitset.test.
  1155. void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable,
  1156. CFITypeCheckKind TCK, SourceLocation Loc);
  1157. /// CanDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
  1158. /// expr can be devirtualized.
  1159. bool CanDevirtualizeMemberFunctionCall(const Expr *Base,
  1160. const CXXMethodDecl *MD);
  1161. /// EnterDtorCleanups - Enter the cleanups necessary to complete the
  1162. /// given phase of destruction for a destructor. The end result
  1163. /// should call destructors on members and base classes in reverse
  1164. /// order of their construction.
  1165. void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
  1166. /// ShouldInstrumentFunction - Return true if the current function should be
  1167. /// instrumented with __cyg_profile_func_* calls
  1168. bool ShouldInstrumentFunction();
  1169. /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
  1170. /// instrumentation function with the current function and the call site, if
  1171. /// function instrumentation is enabled.
  1172. void EmitFunctionInstrumentation(const char *Fn);
  1173. /// EmitMCountInstrumentation - Emit call to .mcount.
  1174. void EmitMCountInstrumentation();
  1175. /// EmitFunctionProlog - Emit the target specific LLVM code to load the
  1176. /// arguments for the given function. This is also responsible for naming the
  1177. /// LLVM function arguments.
  1178. void EmitFunctionProlog(const CGFunctionInfo &FI,
  1179. llvm::Function *Fn,
  1180. const FunctionArgList &Args);
  1181. /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
  1182. /// given temporary.
  1183. void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc,
  1184. SourceLocation EndLoc);
  1185. /// EmitStartEHSpec - Emit the start of the exception spec.
  1186. void EmitStartEHSpec(const Decl *D);
  1187. /// EmitEndEHSpec - Emit the end of the exception spec.
  1188. void EmitEndEHSpec(const Decl *D);
  1189. /// getTerminateLandingPad - Return a landing pad that just calls terminate.
  1190. llvm::BasicBlock *getTerminateLandingPad();
  1191. /// getTerminateHandler - Return a handler (not a landing pad, just
  1192. /// a catch handler) that just calls terminate. This is used when
  1193. /// a terminate scope encloses a try.
  1194. llvm::BasicBlock *getTerminateHandler();
  1195. llvm::Type *ConvertTypeForMem(QualType T);
  1196. llvm::Type *ConvertType(QualType T);
  1197. llvm::Type *ConvertType(const TypeDecl *T) {
  1198. return ConvertType(getContext().getTypeDeclType(T));
  1199. }
  1200. /// LoadObjCSelf - Load the value of self. This function is only valid while
  1201. /// generating code for an Objective-C method.
  1202. llvm::Value *LoadObjCSelf();
  1203. /// TypeOfSelfObject - Return type of object that this self represents.
  1204. QualType TypeOfSelfObject();
  1205. /// hasAggregateLLVMType - Return true if the specified AST type will map into
  1206. /// an aggregate LLVM type or is void.
  1207. static TypeEvaluationKind getEvaluationKind(QualType T);
  1208. static bool hasScalarEvaluationKind(QualType T) {
  1209. return getEvaluationKind(T) == TEK_Scalar;
  1210. }
  1211. static bool hasAggregateEvaluationKind(QualType T) {
  1212. return getEvaluationKind(T) == TEK_Aggregate;
  1213. }
  1214. /// createBasicBlock - Create an LLVM basic block.
  1215. llvm::BasicBlock *createBasicBlock(const Twine &name = "",
  1216. llvm::Function *parent = nullptr,
  1217. llvm::BasicBlock *before = nullptr) {
  1218. #ifdef NDEBUG
  1219. return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before);
  1220. #else
  1221. return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
  1222. #endif
  1223. }
  1224. /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
  1225. /// label maps to.
  1226. JumpDest getJumpDestForLabel(const LabelDecl *S);
  1227. /// SimplifyForwardingBlocks - If the given basic block is only a branch to
  1228. /// another basic block, simplify it. This assumes that no other code could
  1229. /// potentially reference the basic block.
  1230. void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
  1231. /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
  1232. /// adding a fall-through branch from the current insert block if
  1233. /// necessary. It is legal to call this function even if there is no current
  1234. /// insertion point.
  1235. ///
  1236. /// IsFinished - If true, indicates that the caller has finished emitting
  1237. /// branches to the given block and does not expect to emit code into it. This
  1238. /// means the block can be ignored if it is unreachable.
  1239. void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
  1240. /// EmitBlockAfterUses - Emit the given block somewhere hopefully
  1241. /// near its uses, and leave the insertion point in it.
  1242. void EmitBlockAfterUses(llvm::BasicBlock *BB);
  1243. /// EmitBranch - Emit a branch to the specified basic block from the current
  1244. /// insert block, taking care to avoid creation of branches from dummy
  1245. /// blocks. It is legal to call this function even if there is no current
  1246. /// insertion point.
  1247. ///
  1248. /// This function clears the current insertion point. The caller should follow
  1249. /// calls to this function with calls to Emit*Block prior to generation new
  1250. /// code.
  1251. void EmitBranch(llvm::BasicBlock *Block);
  1252. /// HaveInsertPoint - True if an insertion point is defined. If not, this
  1253. /// indicates that the current code being emitted is unreachable.
  1254. bool HaveInsertPoint() const {
  1255. return Builder.GetInsertBlock() != nullptr;
  1256. }
  1257. /// EnsureInsertPoint - Ensure that an insertion point is defined so that
  1258. /// emitted IR has a place to go. Note that by definition, if this function
  1259. /// creates a block then that block is unreachable; callers may do better to
  1260. /// detect when no insertion point is defined and simply skip IR generation.
  1261. void EnsureInsertPoint() {
  1262. if (!HaveInsertPoint())
  1263. EmitBlock(createBasicBlock());
  1264. }
  1265. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  1266. /// specified stmt yet.
  1267. void ErrorUnsupported(const Stmt *S, const char *Type);
  1268. //===--------------------------------------------------------------------===//
  1269. // Helpers
  1270. //===--------------------------------------------------------------------===//
  1271. LValue MakeAddrLValue(Address Addr, QualType T,
  1272. AlignmentSource AlignSource = AlignmentSource::Type) {
  1273. return LValue::MakeAddr(Addr, T, getContext(), AlignSource,
  1274. CGM.getTBAAInfo(T));
  1275. }
  1276. LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment,
  1277. AlignmentSource AlignSource = AlignmentSource::Type) {
  1278. return LValue::MakeAddr(Address(V, Alignment), T, getContext(),
  1279. AlignSource, CGM.getTBAAInfo(T));
  1280. }
  1281. LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T);
  1282. LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T);
  1283. CharUnits getNaturalTypeAlignment(QualType T,
  1284. AlignmentSource *Source = nullptr,
  1285. bool forPointeeType = false);
  1286. CharUnits getNaturalPointeeTypeAlignment(QualType T,
  1287. AlignmentSource *Source = nullptr);
  1288. Address EmitLoadOfReference(Address Ref, const ReferenceType *RefTy,
  1289. AlignmentSource *Source = nullptr);
  1290. LValue EmitLoadOfReferenceLValue(Address Ref, const ReferenceType *RefTy);
  1291. /// CreateTempAlloca - This creates a alloca and inserts it into the entry
  1292. /// block. The caller is responsible for setting an appropriate alignment on
  1293. /// the alloca.
  1294. llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty,
  1295. const Twine &Name = "tmp");
  1296. Address CreateTempAlloca(llvm::Type *Ty, CharUnits align,
  1297. const Twine &Name = "tmp");
  1298. /// CreateDefaultAlignedTempAlloca - This creates an alloca with the
  1299. /// default ABI alignment of the given LLVM type.
  1300. ///
  1301. /// IMPORTANT NOTE: This is *not* generally the right alignment for
  1302. /// any given AST type that happens to have been lowered to the
  1303. /// given IR type. This should only ever be used for function-local,
  1304. /// IR-driven manipulations like saving and restoring a value. Do
  1305. /// not hand this address off to arbitrary IRGen routines, and especially
  1306. /// do not pass it as an argument to a function that might expect a
  1307. /// properly ABI-aligned value.
  1308. Address CreateDefaultAlignTempAlloca(llvm::Type *Ty,
  1309. const Twine &Name = "tmp");
  1310. /// InitTempAlloca - Provide an initial value for the given alloca which
  1311. /// will be observable at all locations in the function.
  1312. ///
  1313. /// The address should be something that was returned from one of
  1314. /// the CreateTempAlloca or CreateMemTemp routines, and the
  1315. /// initializer must be valid in the entry block (i.e. it must
  1316. /// either be a constant or an argument value).
  1317. void InitTempAlloca(Address Alloca, llvm::Value *Value);
  1318. /// CreateIRTemp - Create a temporary IR object of the given type, with
  1319. /// appropriate alignment. This routine should only be used when an temporary
  1320. /// value needs to be stored into an alloca (for example, to avoid explicit
  1321. /// PHI construction), but the type is the IR type, not the type appropriate
  1322. /// for storing in memory.
  1323. ///
  1324. /// That is, this is exactly equivalent to CreateMemTemp, but calling
  1325. /// ConvertType instead of ConvertTypeForMem.
  1326. Address CreateIRTemp(QualType T, const Twine &Name = "tmp");
  1327. /// CreateMemTemp - Create a temporary memory object of the given type, with
  1328. /// appropriate alignment.
  1329. Address CreateMemTemp(QualType T, const Twine &Name = "tmp");
  1330. Address CreateMemTemp(QualType T, CharUnits Align, const Twine &Name = "tmp");
  1331. /// CreateAggTemp - Create a temporary memory object for the given
  1332. /// aggregate type.
  1333. AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") {
  1334. return AggValueSlot::forAddr(CreateMemTemp(T, Name),
  1335. T.getQualifiers(),
  1336. AggValueSlot::IsNotDestructed,
  1337. AggValueSlot::DoesNotNeedGCBarriers,
  1338. AggValueSlot::IsNotAliased);
  1339. }
  1340. /// CreateInAllocaTmp - Create a temporary memory object for the given
  1341. /// aggregate type.
  1342. AggValueSlot CreateInAllocaTmp(QualType T, const Twine &Name = "inalloca");
  1343. /// Emit a cast to void* in the appropriate address space.
  1344. llvm::Value *EmitCastToVoidPtr(llvm::Value *value);
  1345. /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
  1346. /// expression and compare the result against zero, returning an Int1Ty value.
  1347. llvm::Value *EvaluateExprAsBool(const Expr *E);
  1348. /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
  1349. void EmitIgnoredExpr(const Expr *E);
  1350. /// EmitAnyExpr - Emit code to compute the specified expression which can have
  1351. /// any type. The result is returned as an RValue struct. If this is an
  1352. /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
  1353. /// the result should be returned.
  1354. ///
  1355. /// \param ignoreResult True if the resulting value isn't used.
  1356. RValue EmitAnyExpr(const Expr *E,
  1357. AggValueSlot aggSlot = AggValueSlot::ignored(),
  1358. bool ignoreResult = false);
  1359. // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
  1360. // or the value of the expression, depending on how va_list is defined.
  1361. Address EmitVAListRef(const Expr *E);
  1362. /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
  1363. /// always be accessible even if no aggregate location is provided.
  1364. RValue EmitAnyExprToTemp(const Expr *E);
  1365. /// EmitAnyExprToMem - Emits the code necessary to evaluate an
  1366. /// arbitrary expression into the given memory location.
  1367. void EmitAnyExprToMem(const Expr *E, Address Location,
  1368. Qualifiers Quals, bool IsInitializer);
  1369. void EmitAnyExprToExn(const Expr *E, Address Addr);
  1370. /// EmitExprAsInit - Emits the code necessary to initialize a
  1371. /// location in memory with the given initializer.
  1372. void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue,
  1373. bool capturedByInit);
  1374. /// hasVolatileMember - returns true if aggregate type has a volatile
  1375. /// member.
  1376. bool hasVolatileMember(QualType T) {
  1377. if (const RecordType *RT = T->getAs<RecordType>()) {
  1378. const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
  1379. return RD->hasVolatileMember();
  1380. }
  1381. return false;
  1382. }
  1383. /// EmitAggregateCopy - Emit an aggregate assignment.
  1384. ///
  1385. /// The difference to EmitAggregateCopy is that tail padding is not copied.
  1386. /// This is required for correctness when assigning non-POD structures in C++.
  1387. void EmitAggregateAssign(Address DestPtr, Address SrcPtr,
  1388. QualType EltTy) {
  1389. bool IsVolatile = hasVolatileMember(EltTy);
  1390. EmitAggregateCopy(DestPtr, SrcPtr, EltTy, IsVolatile, true);
  1391. }
  1392. void EmitAggregateCopyCtor(Address DestPtr, Address SrcPtr,
  1393. QualType DestTy, QualType SrcTy) {
  1394. EmitAggregateCopy(DestPtr, SrcPtr, SrcTy, /*IsVolatile=*/false,
  1395. /*IsAssignment=*/false);
  1396. }
  1397. /// EmitAggregateCopy - Emit an aggregate copy.
  1398. ///
  1399. /// \param isVolatile - True iff either the source or the destination is
  1400. /// volatile.
  1401. /// \param isAssignment - If false, allow padding to be copied. This often
  1402. /// yields more efficient.
  1403. void EmitAggregateCopy(Address DestPtr, Address SrcPtr,
  1404. QualType EltTy, bool isVolatile=false,
  1405. bool isAssignment = false);
  1406. /// StartBlock - Start new block named N. If insert block is a dummy block
  1407. /// then reuse it.
  1408. void StartBlock(const char *N);
  1409. /// GetAddrOfLocalVar - Return the address of a local variable.
  1410. Address GetAddrOfLocalVar(const VarDecl *VD) {
  1411. auto it = LocalDeclMap.find(VD);
  1412. assert(it != LocalDeclMap.end() &&
  1413. "Invalid argument to GetAddrOfLocalVar(), no decl!");
  1414. return it->second;
  1415. }
  1416. /// getOpaqueLValueMapping - Given an opaque value expression (which
  1417. /// must be mapped to an l-value), return its mapping.
  1418. const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) {
  1419. assert(OpaqueValueMapping::shouldBindAsLValue(e));
  1420. llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
  1421. it = OpaqueLValues.find(e);
  1422. assert(it != OpaqueLValues.end() && "no mapping for opaque value!");
  1423. return it->second;
  1424. }
  1425. /// getOpaqueRValueMapping - Given an opaque value expression (which
  1426. /// must be mapped to an r-value), return its mapping.
  1427. const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) {
  1428. assert(!OpaqueValueMapping::shouldBindAsLValue(e));
  1429. llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
  1430. it = OpaqueRValues.find(e);
  1431. assert(it != OpaqueRValues.end() && "no mapping for opaque value!");
  1432. return it->second;
  1433. }
  1434. /// getAccessedFieldNo - Given an encoded value and a result number, return
  1435. /// the input field number being accessed.
  1436. static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
  1437. llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
  1438. llvm::BasicBlock *GetIndirectGotoBlock();
  1439. /// EmitNullInitialization - Generate code to set a value of the given type to
  1440. /// null, If the type contains data member pointers, they will be initialized
  1441. /// to -1 in accordance with the Itanium C++ ABI.
  1442. void EmitNullInitialization(Address DestPtr, QualType Ty);
  1443. // EmitVAArg - Generate code to get an argument from the passed in pointer
  1444. // and update it accordingly. The return value is a pointer to the argument.
  1445. // FIXME: We should be able to get rid of this method and use the va_arg
  1446. // instruction in LLVM instead once it works well enough.
  1447. Address EmitVAArg(Address VAListAddr, QualType Ty);
  1448. /// emitArrayLength - Compute the length of an array, even if it's a
  1449. /// VLA, and drill down to the base element type.
  1450. llvm::Value *emitArrayLength(const ArrayType *arrayType,
  1451. QualType &baseType,
  1452. Address &addr);
  1453. /// EmitVLASize - Capture all the sizes for the VLA expressions in
  1454. /// the given variably-modified type and store them in the VLASizeMap.
  1455. ///
  1456. /// This function can be called with a null (unreachable) insert point.
  1457. void EmitVariablyModifiedType(QualType Ty);
  1458. /// getVLASize - Returns an LLVM value that corresponds to the size,
  1459. /// in non-variably-sized elements, of a variable length array type,
  1460. /// plus that largest non-variably-sized element type. Assumes that
  1461. /// the type has already been emitted with EmitVariablyModifiedType.
  1462. std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla);
  1463. std::pair<llvm::Value*,QualType> getVLASize(QualType vla);
  1464. /// LoadCXXThis - Load the value of 'this'. This function is only valid while
  1465. /// generating code for an C++ member function.
  1466. llvm::Value *LoadCXXThis() {
  1467. assert(CXXThisValue && "no 'this' value for this function");
  1468. return CXXThisValue;
  1469. }
  1470. Address LoadCXXThisAddress();
  1471. /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
  1472. /// virtual bases.
  1473. // FIXME: Every place that calls LoadCXXVTT is something
  1474. // that needs to be abstracted properly.
  1475. llvm::Value *LoadCXXVTT() {
  1476. assert(CXXStructorImplicitParamValue && "no VTT value for this function");
  1477. return CXXStructorImplicitParamValue;
  1478. }
  1479. /// LoadCXXStructorImplicitParam - Load the implicit parameter
  1480. /// for a constructor/destructor.
  1481. llvm::Value *LoadCXXStructorImplicitParam() {
  1482. assert(CXXStructorImplicitParamValue &&
  1483. "no implicit argument value for this function");
  1484. return CXXStructorImplicitParamValue;
  1485. }
  1486. /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
  1487. /// complete class to the given direct base.
  1488. Address
  1489. GetAddressOfDirectBaseInCompleteClass(Address Value,
  1490. const CXXRecordDecl *Derived,
  1491. const CXXRecordDecl *Base,
  1492. bool BaseIsVirtual);
  1493. static bool ShouldNullCheckClassCastValue(const CastExpr *Cast);
  1494. /// GetAddressOfBaseClass - This function will add the necessary delta to the
  1495. /// load of 'this' and returns address of the base class.
  1496. Address GetAddressOfBaseClass(Address Value,
  1497. const CXXRecordDecl *Derived,
  1498. CastExpr::path_const_iterator PathBegin,
  1499. CastExpr::path_const_iterator PathEnd,
  1500. bool NullCheckValue, SourceLocation Loc);
  1501. Address GetAddressOfDerivedClass(Address Value,
  1502. const CXXRecordDecl *Derived,
  1503. CastExpr::path_const_iterator PathBegin,
  1504. CastExpr::path_const_iterator PathEnd,
  1505. bool NullCheckValue);
  1506. /// GetVTTParameter - Return the VTT parameter that should be passed to a
  1507. /// base constructor/destructor with virtual bases.
  1508. /// FIXME: VTTs are Itanium ABI-specific, so the definition should move
  1509. /// to ItaniumCXXABI.cpp together with all the references to VTT.
  1510. llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase,
  1511. bool Delegating);
  1512. void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1513. CXXCtorType CtorType,
  1514. const FunctionArgList &Args,
  1515. SourceLocation Loc);
  1516. // It's important not to confuse this and the previous function. Delegating
  1517. // constructors are the C++0x feature. The constructor delegate optimization
  1518. // is used to reduce duplication in the base and complete consturctors where
  1519. // they are substantially the same.
  1520. void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1521. const FunctionArgList &Args);
  1522. void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
  1523. bool ForVirtualBase, bool Delegating,
  1524. Address This, const CXXConstructExpr *E);
  1525. void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
  1526. Address This, Address Src,
  1527. const CXXConstructExpr *E);
  1528. void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
  1529. const ConstantArrayType *ArrayTy,
  1530. Address ArrayPtr,
  1531. const CXXConstructExpr *E,
  1532. bool ZeroInitialization = false);
  1533. void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
  1534. llvm::Value *NumElements,
  1535. Address ArrayPtr,
  1536. const CXXConstructExpr *E,
  1537. bool ZeroInitialization = false);
  1538. static Destroyer destroyCXXObject;
  1539. void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
  1540. bool ForVirtualBase, bool Delegating,
  1541. Address This);
  1542. void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
  1543. llvm::Type *ElementTy, Address NewPtr,
  1544. llvm::Value *NumElements,
  1545. llvm::Value *AllocSizeWithoutCookie);
  1546. void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
  1547. Address Ptr);
  1548. llvm::Value *EmitLifetimeStart(uint64_t Size, llvm::Value *Addr);
  1549. void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr);
  1550. llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
  1551. void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
  1552. void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
  1553. QualType DeleteTy);
  1554. RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
  1555. const Expr *Arg, bool IsDelete);
  1556. llvm::Value *EmitCXXTypeidExpr(const CXXTypeidExpr *E);
  1557. llvm::Value *EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE);
  1558. Address EmitCXXUuidofExpr(const CXXUuidofExpr *E);
  1559. /// \brief Situations in which we might emit a check for the suitability of a
  1560. /// pointer or glvalue.
  1561. enum TypeCheckKind {
  1562. /// Checking the operand of a load. Must be suitably sized and aligned.
  1563. TCK_Load,
  1564. /// Checking the destination of a store. Must be suitably sized and aligned.
  1565. TCK_Store,
  1566. /// Checking the bound value in a reference binding. Must be suitably sized
  1567. /// and aligned, but is not required to refer to an object (until the
  1568. /// reference is used), per core issue 453.
  1569. TCK_ReferenceBinding,
  1570. /// Checking the object expression in a non-static data member access. Must
  1571. /// be an object within its lifetime.
  1572. TCK_MemberAccess,
  1573. /// Checking the 'this' pointer for a call to a non-static member function.
  1574. /// Must be an object within its lifetime.
  1575. TCK_MemberCall,
  1576. /// Checking the 'this' pointer for a constructor call.
  1577. TCK_ConstructorCall,
  1578. /// Checking the operand of a static_cast to a derived pointer type. Must be
  1579. /// null or an object within its lifetime.
  1580. TCK_DowncastPointer,
  1581. /// Checking the operand of a static_cast to a derived reference type. Must
  1582. /// be an object within its lifetime.
  1583. TCK_DowncastReference,
  1584. /// Checking the operand of a cast to a base object. Must be suitably sized
  1585. /// and aligned.
  1586. TCK_Upcast,
  1587. /// Checking the operand of a cast to a virtual base object. Must be an
  1588. /// object within its lifetime.
  1589. TCK_UpcastToVirtualBase
  1590. };
  1591. /// \brief Whether any type-checking sanitizers are enabled. If \c false,
  1592. /// calls to EmitTypeCheck can be skipped.
  1593. bool sanitizePerformTypeCheck() const;
  1594. /// \brief Emit a check that \p V is the address of storage of the
  1595. /// appropriate size and alignment for an object of type \p Type.
  1596. void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V,
  1597. QualType Type, CharUnits Alignment = CharUnits::Zero(),
  1598. bool SkipNullCheck = false);
  1599. /// \brief Emit a check that \p Base points into an array object, which
  1600. /// we can access at index \p Index. \p Accessed should be \c false if we
  1601. /// this expression is used as an lvalue, for instance in "&Arr[Idx]".
  1602. void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index,
  1603. QualType IndexType, bool Accessed);
  1604. llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
  1605. bool isInc, bool isPre);
  1606. ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
  1607. bool isInc, bool isPre);
  1608. void EmitAlignmentAssumption(llvm::Value *PtrValue, unsigned Alignment,
  1609. llvm::Value *OffsetValue = nullptr) {
  1610. Builder.CreateAlignmentAssumption(CGM.getDataLayout(), PtrValue, Alignment,
  1611. OffsetValue);
  1612. }
  1613. //===--------------------------------------------------------------------===//
  1614. // Declaration Emission
  1615. //===--------------------------------------------------------------------===//
  1616. /// EmitDecl - Emit a declaration.
  1617. ///
  1618. /// This function can be called with a null (unreachable) insert point.
  1619. void EmitDecl(const Decl &D);
  1620. /// EmitVarDecl - Emit a local variable declaration.
  1621. ///
  1622. /// This function can be called with a null (unreachable) insert point.
  1623. void EmitVarDecl(const VarDecl &D);
  1624. void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue,
  1625. bool capturedByInit);
  1626. void EmitScalarInit(llvm::Value *init, LValue lvalue);
  1627. typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
  1628. llvm::Value *Address);
  1629. /// \brief Determine whether the given initializer is trivial in the sense
  1630. /// that it requires no code to be generated.
  1631. bool isTrivialInitializer(const Expr *Init);
  1632. /// EmitAutoVarDecl - Emit an auto variable declaration.
  1633. ///
  1634. /// This function can be called with a null (unreachable) insert point.
  1635. void EmitAutoVarDecl(const VarDecl &D);
  1636. class AutoVarEmission {
  1637. friend class CodeGenFunction;
  1638. const VarDecl *Variable;
  1639. /// The address of the alloca. Invalid if the variable was emitted
  1640. /// as a global constant.
  1641. Address Addr;
  1642. llvm::Value *NRVOFlag;
  1643. /// True if the variable is a __block variable.
  1644. bool IsByRef;
  1645. /// True if the variable is of aggregate type and has a constant
  1646. /// initializer.
  1647. bool IsConstantAggregate;
  1648. /// Non-null if we should use lifetime annotations.
  1649. llvm::Value *SizeForLifetimeMarkers;
  1650. struct Invalid {};
  1651. AutoVarEmission(Invalid) : Variable(nullptr), Addr(Address::invalid()) {}
  1652. AutoVarEmission(const VarDecl &variable)
  1653. : Variable(&variable), Addr(Address::invalid()), NRVOFlag(nullptr),
  1654. IsByRef(false), IsConstantAggregate(false),
  1655. SizeForLifetimeMarkers(nullptr) {}
  1656. bool wasEmittedAsGlobal() const { return !Addr.isValid(); }
  1657. public:
  1658. static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
  1659. bool useLifetimeMarkers() const {
  1660. return SizeForLifetimeMarkers != nullptr;
  1661. }
  1662. llvm::Value *getSizeForLifetimeMarkers() const {
  1663. assert(useLifetimeMarkers());
  1664. return SizeForLifetimeMarkers;
  1665. }
  1666. /// Returns the raw, allocated address, which is not necessarily
  1667. /// the address of the object itself.
  1668. Address getAllocatedAddress() const {
  1669. return Addr;
  1670. }
  1671. /// Returns the address of the object within this declaration.
  1672. /// Note that this does not chase the forwarding pointer for
  1673. /// __block decls.
  1674. Address getObjectAddress(CodeGenFunction &CGF) const {
  1675. if (!IsByRef) return Addr;
  1676. return CGF.emitBlockByrefAddress(Addr, Variable, /*forward*/ false);
  1677. }
  1678. };
  1679. AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
  1680. void EmitAutoVarInit(const AutoVarEmission &emission);
  1681. void EmitAutoVarCleanups(const AutoVarEmission &emission);
  1682. void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
  1683. QualType::DestructionKind dtorKind);
  1684. void EmitStaticVarDecl(const VarDecl &D,
  1685. llvm::GlobalValue::LinkageTypes Linkage);
  1686. class ParamValue {
  1687. llvm::Value *Value;
  1688. unsigned Alignment;
  1689. ParamValue(llvm::Value *V, unsigned A) : Value(V), Alignment(A) {}
  1690. public:
  1691. static ParamValue forDirect(llvm::Value *value) {
  1692. return ParamValue(value, 0);
  1693. }
  1694. static ParamValue forIndirect(Address addr) {
  1695. assert(!addr.getAlignment().isZero());
  1696. return ParamValue(addr.getPointer(), addr.getAlignment().getQuantity());
  1697. }
  1698. bool isIndirect() const { return Alignment != 0; }
  1699. llvm::Value *getAnyValue() const { return Value; }
  1700. llvm::Value *getDirectValue() const {
  1701. assert(!isIndirect());
  1702. return Value;
  1703. }
  1704. Address getIndirectAddress() const {
  1705. assert(isIndirect());
  1706. return Address(Value, CharUnits::fromQuantity(Alignment));
  1707. }
  1708. };
  1709. /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
  1710. void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo);
  1711. /// protectFromPeepholes - Protect a value that we're intending to
  1712. /// store to the side, but which will probably be used later, from
  1713. /// aggressive peepholing optimizations that might delete it.
  1714. ///
  1715. /// Pass the result to unprotectFromPeepholes to declare that
  1716. /// protection is no longer required.
  1717. ///
  1718. /// There's no particular reason why this shouldn't apply to
  1719. /// l-values, it's just that no existing peepholes work on pointers.
  1720. PeepholeProtection protectFromPeepholes(RValue rvalue);
  1721. void unprotectFromPeepholes(PeepholeProtection protection);
  1722. //===--------------------------------------------------------------------===//
  1723. // Statement Emission
  1724. //===--------------------------------------------------------------------===//
  1725. /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
  1726. void EmitStopPoint(const Stmt *S);
  1727. /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
  1728. /// this function even if there is no current insertion point.
  1729. ///
  1730. /// This function may clear the current insertion point; callers should use
  1731. /// EnsureInsertPoint if they wish to subsequently generate code without first
  1732. /// calling EmitBlock, EmitBranch, or EmitStmt.
  1733. void EmitStmt(const Stmt *S);
  1734. /// EmitSimpleStmt - Try to emit a "simple" statement which does not
  1735. /// necessarily require an insertion point or debug information; typically
  1736. /// because the statement amounts to a jump or a container of other
  1737. /// statements.
  1738. ///
  1739. /// \return True if the statement was handled.
  1740. bool EmitSimpleStmt(const Stmt *S);
  1741. Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
  1742. AggValueSlot AVS = AggValueSlot::ignored());
  1743. Address EmitCompoundStmtWithoutScope(const CompoundStmt &S,
  1744. bool GetLast = false,
  1745. AggValueSlot AVS =
  1746. AggValueSlot::ignored());
  1747. /// EmitLabel - Emit the block for the given label. It is legal to call this
  1748. /// function even if there is no current insertion point.
  1749. void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
  1750. void EmitLabelStmt(const LabelStmt &S);
  1751. void EmitAttributedStmt(const AttributedStmt &S);
  1752. void EmitGotoStmt(const GotoStmt &S);
  1753. void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
  1754. void EmitIfStmt(const IfStmt &S);
  1755. void EmitWhileStmt(const WhileStmt &S,
  1756. ArrayRef<const Attr *> Attrs = None);
  1757. void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None);
  1758. void EmitForStmt(const ForStmt &S,
  1759. ArrayRef<const Attr *> Attrs = None);
  1760. void EmitReturnStmt(const ReturnStmt &S);
  1761. void EmitDeclStmt(const DeclStmt &S);
  1762. void EmitBreakStmt(const BreakStmt &S);
  1763. void EmitContinueStmt(const ContinueStmt &S);
  1764. void EmitSwitchStmt(const SwitchStmt &S);
  1765. void EmitDefaultStmt(const DefaultStmt &S);
  1766. void EmitCaseStmt(const CaseStmt &S);
  1767. void EmitCaseStmtRange(const CaseStmt &S);
  1768. void EmitAsmStmt(const AsmStmt &S);
  1769. void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
  1770. void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
  1771. void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
  1772. void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
  1773. void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S);
  1774. void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
  1775. void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
  1776. void EmitCXXTryStmt(const CXXTryStmt &S);
  1777. void EmitSEHTryStmt(const SEHTryStmt &S);
  1778. void EmitSEHLeaveStmt(const SEHLeaveStmt &S);
  1779. void EnterSEHTryStmt(const SEHTryStmt &S);
  1780. void ExitSEHTryStmt(const SEHTryStmt &S);
  1781. void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter,
  1782. const Stmt *OutlinedStmt);
  1783. llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
  1784. const SEHExceptStmt &Except);
  1785. llvm::Function *GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
  1786. const SEHFinallyStmt &Finally);
  1787. void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
  1788. llvm::Value *ParentFP,
  1789. llvm::Value *EntryEBP);
  1790. llvm::Value *EmitSEHExceptionCode();
  1791. llvm::Value *EmitSEHExceptionInfo();
  1792. llvm::Value *EmitSEHAbnormalTermination();
  1793. /// Scan the outlined statement for captures from the parent function. For
  1794. /// each capture, mark the capture as escaped and emit a call to
  1795. /// llvm.localrecover. Insert the localrecover result into the LocalDeclMap.
  1796. void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt,
  1797. bool IsFilter);
  1798. /// Recovers the address of a local in a parent function. ParentVar is the
  1799. /// address of the variable used in the immediate parent function. It can
  1800. /// either be an alloca or a call to llvm.localrecover if there are nested
  1801. /// outlined functions. ParentFP is the frame pointer of the outermost parent
  1802. /// frame.
  1803. Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
  1804. Address ParentVar,
  1805. llvm::Value *ParentFP);
  1806. void EmitCXXForRangeStmt(const CXXForRangeStmt &S,
  1807. ArrayRef<const Attr *> Attrs = None);
  1808. LValue InitCapturedStruct(const CapturedStmt &S);
  1809. llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K);
  1810. void GenerateCapturedStmtFunctionProlog(const CapturedStmt &S);
  1811. llvm::Function *GenerateCapturedStmtFunctionEpilog(const CapturedStmt &S);
  1812. llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S);
  1813. Address GenerateCapturedStmtArgument(const CapturedStmt &S);
  1814. /// \brief Perform element by element copying of arrays with type \a
  1815. /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure
  1816. /// generated by \a CopyGen.
  1817. ///
  1818. /// \param DestAddr Address of the destination array.
  1819. /// \param SrcAddr Address of the source array.
  1820. /// \param OriginalType Type of destination and source arrays.
  1821. /// \param CopyGen Copying procedure that copies value of single array element
  1822. /// to another single array element.
  1823. void EmitOMPAggregateAssign(
  1824. Address DestAddr, Address SrcAddr, QualType OriginalType,
  1825. const llvm::function_ref<void(Address, Address)> &CopyGen);
  1826. /// \brief Emit proper copying of data from one variable to another.
  1827. ///
  1828. /// \param OriginalType Original type of the copied variables.
  1829. /// \param DestAddr Destination address.
  1830. /// \param SrcAddr Source address.
  1831. /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has
  1832. /// type of the base array element).
  1833. /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of
  1834. /// the base array element).
  1835. /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a
  1836. /// DestVD.
  1837. void EmitOMPCopy(QualType OriginalType,
  1838. Address DestAddr, Address SrcAddr,
  1839. const VarDecl *DestVD, const VarDecl *SrcVD,
  1840. const Expr *Copy);
  1841. /// \brief Emit atomic update code for constructs: \a X = \a X \a BO \a E or
  1842. /// \a X = \a E \a BO \a E.
  1843. ///
  1844. /// \param X Value to be updated.
  1845. /// \param E Update value.
  1846. /// \param BO Binary operation for update operation.
  1847. /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update
  1848. /// expression, false otherwise.
  1849. /// \param AO Atomic ordering of the generated atomic instructions.
  1850. /// \param CommonGen Code generator for complex expressions that cannot be
  1851. /// expressed through atomicrmw instruction.
  1852. /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was
  1853. /// generated, <false, RValue::get(nullptr)> otherwise.
  1854. std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr(
  1855. LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
  1856. llvm::AtomicOrdering AO, SourceLocation Loc,
  1857. const llvm::function_ref<RValue(RValue)> &CommonGen);
  1858. bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
  1859. OMPPrivateScope &PrivateScope);
  1860. void EmitOMPPrivateClause(const OMPExecutableDirective &D,
  1861. OMPPrivateScope &PrivateScope);
  1862. /// \brief Emit code for copyin clause in \a D directive. The next code is
  1863. /// generated at the start of outlined functions for directives:
  1864. /// \code
  1865. /// threadprivate_var1 = master_threadprivate_var1;
  1866. /// operator=(threadprivate_var2, master_threadprivate_var2);
  1867. /// ...
  1868. /// __kmpc_barrier(&loc, global_tid);
  1869. /// \endcode
  1870. ///
  1871. /// \param D OpenMP directive possibly with 'copyin' clause(s).
  1872. /// \returns true if at least one copyin variable is found, false otherwise.
  1873. bool EmitOMPCopyinClause(const OMPExecutableDirective &D);
  1874. /// \brief Emit initial code for lastprivate variables. If some variable is
  1875. /// not also firstprivate, then the default initialization is used. Otherwise
  1876. /// initialization of this variable is performed by EmitOMPFirstprivateClause
  1877. /// method.
  1878. ///
  1879. /// \param D Directive that may have 'lastprivate' directives.
  1880. /// \param PrivateScope Private scope for capturing lastprivate variables for
  1881. /// proper codegen in internal captured statement.
  1882. ///
  1883. /// \returns true if there is at least one lastprivate variable, false
  1884. /// otherwise.
  1885. bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D,
  1886. OMPPrivateScope &PrivateScope);
  1887. /// \brief Emit final copying of lastprivate values to original variables at
  1888. /// the end of the worksharing or simd directive.
  1889. ///
  1890. /// \param D Directive that has at least one 'lastprivate' directives.
  1891. /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if
  1892. /// it is the last iteration of the loop code in associated directive, or to
  1893. /// 'i1 false' otherwise. If this item is nullptr, no final check is required.
  1894. void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D,
  1895. llvm::Value *IsLastIterCond = nullptr);
  1896. /// \brief Emit initial code for reduction variables. Creates reduction copies
  1897. /// and initializes them with the values according to OpenMP standard.
  1898. ///
  1899. /// \param D Directive (possibly) with the 'reduction' clause.
  1900. /// \param PrivateScope Private scope for capturing reduction variables for
  1901. /// proper codegen in internal captured statement.
  1902. ///
  1903. void EmitOMPReductionClauseInit(const OMPExecutableDirective &D,
  1904. OMPPrivateScope &PrivateScope);
  1905. /// \brief Emit final update of reduction values to original variables at
  1906. /// the end of the directive.
  1907. ///
  1908. /// \param D Directive that has at least one 'reduction' directives.
  1909. void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D);
  1910. /// \brief Emit initial code for linear variables. Creates private copies
  1911. /// and initializes them with the values according to OpenMP standard.
  1912. ///
  1913. /// \param D Directive (possibly) with the 'linear' clause.
  1914. void EmitOMPLinearClauseInit(const OMPLoopDirective &D);
  1915. void EmitOMPParallelDirective(const OMPParallelDirective &S);
  1916. void EmitOMPSimdDirective(const OMPSimdDirective &S);
  1917. void EmitOMPForDirective(const OMPForDirective &S);
  1918. void EmitOMPForSimdDirective(const OMPForSimdDirective &S);
  1919. void EmitOMPSectionsDirective(const OMPSectionsDirective &S);
  1920. void EmitOMPSectionDirective(const OMPSectionDirective &S);
  1921. void EmitOMPSingleDirective(const OMPSingleDirective &S);
  1922. void EmitOMPMasterDirective(const OMPMasterDirective &S);
  1923. void EmitOMPCriticalDirective(const OMPCriticalDirective &S);
  1924. void EmitOMPParallelForDirective(const OMPParallelForDirective &S);
  1925. void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S);
  1926. void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S);
  1927. void EmitOMPTaskDirective(const OMPTaskDirective &S);
  1928. void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S);
  1929. void EmitOMPBarrierDirective(const OMPBarrierDirective &S);
  1930. void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S);
  1931. void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S);
  1932. void EmitOMPFlushDirective(const OMPFlushDirective &S);
  1933. void EmitOMPOrderedDirective(const OMPOrderedDirective &S);
  1934. void EmitOMPAtomicDirective(const OMPAtomicDirective &S);
  1935. void EmitOMPTargetDirective(const OMPTargetDirective &S);
  1936. void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S);
  1937. void EmitOMPTeamsDirective(const OMPTeamsDirective &S);
  1938. void
  1939. EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S);
  1940. void EmitOMPCancelDirective(const OMPCancelDirective &S);
  1941. /// \brief Emit inner loop of the worksharing/simd construct.
  1942. ///
  1943. /// \param S Directive, for which the inner loop must be emitted.
  1944. /// \param RequiresCleanup true, if directive has some associated private
  1945. /// variables.
  1946. /// \param LoopCond Bollean condition for loop continuation.
  1947. /// \param IncExpr Increment expression for loop control variable.
  1948. /// \param BodyGen Generator for the inner body of the inner loop.
  1949. /// \param PostIncGen Genrator for post-increment code (required for ordered
  1950. /// loop directvies).
  1951. void EmitOMPInnerLoop(
  1952. const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
  1953. const Expr *IncExpr,
  1954. const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
  1955. const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen);
  1956. JumpDest getOMPCancelDestination(OpenMPDirectiveKind Kind);
  1957. private:
  1958. /// Helpers for the OpenMP loop directives.
  1959. void EmitOMPLoopBody(const OMPLoopDirective &D, JumpDest LoopExit);
  1960. void EmitOMPSimdInit(const OMPLoopDirective &D);
  1961. void EmitOMPSimdFinal(const OMPLoopDirective &D);
  1962. /// \brief Emit code for the worksharing loop-based directive.
  1963. /// \return true, if this construct has any lastprivate clause, false -
  1964. /// otherwise.
  1965. bool EmitOMPWorksharingLoop(const OMPLoopDirective &S);
  1966. void EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind,
  1967. const OMPLoopDirective &S,
  1968. OMPPrivateScope &LoopScope, bool Ordered,
  1969. Address LB, Address UB, Address ST,
  1970. Address IL, llvm::Value *Chunk);
  1971. /// \brief Emit code for sections directive.
  1972. OpenMPDirectiveKind EmitSections(const OMPExecutableDirective &S);
  1973. public:
  1974. //===--------------------------------------------------------------------===//
  1975. // LValue Expression Emission
  1976. //===--------------------------------------------------------------------===//
  1977. /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
  1978. RValue GetUndefRValue(QualType Ty);
  1979. /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
  1980. /// and issue an ErrorUnsupported style diagnostic (using the
  1981. /// provided Name).
  1982. RValue EmitUnsupportedRValue(const Expr *E,
  1983. const char *Name);
  1984. /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
  1985. /// an ErrorUnsupported style diagnostic (using the provided Name).
  1986. LValue EmitUnsupportedLValue(const Expr *E,
  1987. const char *Name);
  1988. /// EmitLValue - Emit code to compute a designator that specifies the location
  1989. /// of the expression.
  1990. ///
  1991. /// This can return one of two things: a simple address or a bitfield
  1992. /// reference. In either case, the LLVM Value* in the LValue structure is
  1993. /// guaranteed to be an LLVM pointer type.
  1994. ///
  1995. /// If this returns a bitfield reference, nothing about the pointee type of
  1996. /// the LLVM value is known: For example, it may not be a pointer to an
  1997. /// integer.
  1998. ///
  1999. /// If this returns a normal address, and if the lvalue's C type is fixed
  2000. /// size, this method guarantees that the returned pointer type will point to
  2001. /// an LLVM type of the same size of the lvalue's type. If the lvalue has a
  2002. /// variable length type, this is not possible.
  2003. ///
  2004. LValue EmitLValue(const Expr *E);
  2005. /// \brief Same as EmitLValue but additionally we generate checking code to
  2006. /// guard against undefined behavior. This is only suitable when we know
  2007. /// that the address will be used to access the object.
  2008. LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK);
  2009. RValue convertTempToRValue(Address addr, QualType type,
  2010. SourceLocation Loc);
  2011. void EmitAtomicInit(Expr *E, LValue lvalue);
  2012. bool LValueIsSuitableForInlineAtomic(LValue Src);
  2013. bool typeIsSuitableForInlineAtomic(QualType Ty, bool IsVolatile) const;
  2014. RValue EmitAtomicLoad(LValue LV, SourceLocation SL,
  2015. AggValueSlot Slot = AggValueSlot::ignored());
  2016. RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc,
  2017. llvm::AtomicOrdering AO, bool IsVolatile = false,
  2018. AggValueSlot slot = AggValueSlot::ignored());
  2019. void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit);
  2020. void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO,
  2021. bool IsVolatile, bool isInit);
  2022. std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange(
  2023. LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
  2024. llvm::AtomicOrdering Success = llvm::SequentiallyConsistent,
  2025. llvm::AtomicOrdering Failure = llvm::SequentiallyConsistent,
  2026. bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored());
  2027. void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO,
  2028. const llvm::function_ref<RValue(RValue)> &UpdateOp,
  2029. bool IsVolatile);
  2030. /// EmitToMemory - Change a scalar value from its value
  2031. /// representation to its in-memory representation.
  2032. llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
  2033. /// EmitFromMemory - Change a scalar value from its memory
  2034. /// representation to its value representation.
  2035. llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
  2036. /// EmitLoadOfScalar - Load a scalar value from an address, taking
  2037. /// care to appropriately convert from the memory representation to
  2038. /// the LLVM value representation.
  2039. llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
  2040. SourceLocation Loc,
  2041. AlignmentSource AlignSource =
  2042. AlignmentSource::Type,
  2043. llvm::MDNode *TBAAInfo = nullptr,
  2044. QualType TBAABaseTy = QualType(),
  2045. uint64_t TBAAOffset = 0,
  2046. bool isNontemporal = false);
  2047. /// EmitLoadOfScalar - Load a scalar value from an address, taking
  2048. /// care to appropriately convert from the memory representation to
  2049. /// the LLVM value representation. The l-value must be a simple
  2050. /// l-value.
  2051. llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc);
  2052. /// EmitStoreOfScalar - Store a scalar value to an address, taking
  2053. /// care to appropriately convert from the memory representation to
  2054. /// the LLVM value representation.
  2055. void EmitStoreOfScalar(llvm::Value *Value, Address Addr,
  2056. bool Volatile, QualType Ty,
  2057. AlignmentSource AlignSource = AlignmentSource::Type,
  2058. llvm::MDNode *TBAAInfo = nullptr, bool isInit = false,
  2059. QualType TBAABaseTy = QualType(),
  2060. uint64_t TBAAOffset = 0, bool isNontemporal = false);
  2061. /// EmitStoreOfScalar - Store a scalar value to an address, taking
  2062. /// care to appropriately convert from the memory representation to
  2063. /// the LLVM value representation. The l-value must be a simple
  2064. /// l-value. The isInit flag indicates whether this is an initialization.
  2065. /// If so, atomic qualifiers are ignored and the store is always non-atomic.
  2066. void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false);
  2067. /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
  2068. /// this method emits the address of the lvalue, then loads the result as an
  2069. /// rvalue, returning the rvalue.
  2070. RValue EmitLoadOfLValue(LValue V, SourceLocation Loc);
  2071. RValue EmitLoadOfExtVectorElementLValue(LValue V);
  2072. RValue EmitLoadOfBitfieldLValue(LValue LV);
  2073. RValue EmitLoadOfGlobalRegLValue(LValue LV);
  2074. /// EmitStoreThroughLValue - Store the specified rvalue into the specified
  2075. /// lvalue, where both are guaranteed to the have the same type, and that type
  2076. /// is 'Ty'.
  2077. void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false);
  2078. void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
  2079. void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst);
  2080. /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints
  2081. /// as EmitStoreThroughLValue.
  2082. ///
  2083. /// \param Result [out] - If non-null, this will be set to a Value* for the
  2084. /// bit-field contents after the store, appropriate for use as the result of
  2085. /// an assignment to the bit-field.
  2086. void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
  2087. llvm::Value **Result=nullptr);
  2088. /// Emit an l-value for an assignment (simple or compound) of complex type.
  2089. LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
  2090. LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
  2091. LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E,
  2092. llvm::Value *&Result);
  2093. // Note: only available for agg return types
  2094. LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
  2095. LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
  2096. // Note: only available for agg return types
  2097. LValue EmitCallExprLValue(const CallExpr *E);
  2098. // Note: only available for agg return types
  2099. LValue EmitVAArgExprLValue(const VAArgExpr *E);
  2100. LValue EmitDeclRefLValue(const DeclRefExpr *E);
  2101. LValue EmitReadRegister(const VarDecl *VD);
  2102. LValue EmitStringLiteralLValue(const StringLiteral *E);
  2103. LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
  2104. LValue EmitPredefinedLValue(const PredefinedExpr *E);
  2105. LValue EmitUnaryOpLValue(const UnaryOperator *E);
  2106. LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
  2107. bool Accessed = false);
  2108. LValue EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
  2109. bool IsLowerBound = true);
  2110. LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
  2111. LValue EmitMemberExpr(const MemberExpr *E);
  2112. LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
  2113. LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
  2114. LValue EmitInitListLValue(const InitListExpr *E);
  2115. LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E);
  2116. LValue EmitCastLValue(const CastExpr *E);
  2117. LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  2118. LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
  2119. Address EmitExtVectorElementLValue(LValue V);
  2120. RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc);
  2121. Address EmitArrayToPointerDecay(const Expr *Array,
  2122. AlignmentSource *AlignSource = nullptr);
  2123. class ConstantEmission {
  2124. llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference;
  2125. ConstantEmission(llvm::Constant *C, bool isReference)
  2126. : ValueAndIsReference(C, isReference) {}
  2127. public:
  2128. ConstantEmission() {}
  2129. static ConstantEmission forReference(llvm::Constant *C) {
  2130. return ConstantEmission(C, true);
  2131. }
  2132. static ConstantEmission forValue(llvm::Constant *C) {
  2133. return ConstantEmission(C, false);
  2134. }
  2135. explicit operator bool() const {
  2136. return ValueAndIsReference.getOpaqueValue() != nullptr;
  2137. }
  2138. bool isReference() const { return ValueAndIsReference.getInt(); }
  2139. LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const {
  2140. assert(isReference());
  2141. return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(),
  2142. refExpr->getType());
  2143. }
  2144. llvm::Constant *getValue() const {
  2145. assert(!isReference());
  2146. return ValueAndIsReference.getPointer();
  2147. }
  2148. };
  2149. ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr);
  2150. RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e,
  2151. AggValueSlot slot = AggValueSlot::ignored());
  2152. LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e);
  2153. llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
  2154. const ObjCIvarDecl *Ivar);
  2155. LValue EmitLValueForField(LValue Base, const FieldDecl* Field);
  2156. LValue EmitLValueForLambdaField(const FieldDecl *Field);
  2157. /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
  2158. /// if the Field is a reference, this will return the address of the reference
  2159. /// and not the address of the value stored in the reference.
  2160. LValue EmitLValueForFieldInitialization(LValue Base,
  2161. const FieldDecl* Field);
  2162. LValue EmitLValueForIvar(QualType ObjectTy,
  2163. llvm::Value* Base, const ObjCIvarDecl *Ivar,
  2164. unsigned CVRQualifiers);
  2165. LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
  2166. LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
  2167. LValue EmitLambdaLValue(const LambdaExpr *E);
  2168. LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
  2169. LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E);
  2170. LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
  2171. LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
  2172. LValue EmitStmtExprLValue(const StmtExpr *E);
  2173. LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
  2174. LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
  2175. void EmitDeclRefExprDbgValue(const DeclRefExpr *E, llvm::Constant *Init);
  2176. //===--------------------------------------------------------------------===//
  2177. // Scalar Expression Emission
  2178. //===--------------------------------------------------------------------===//
  2179. /// EmitCall - Generate a call of the given function, expecting the given
  2180. /// result type, and using the given argument list which specifies both the
  2181. /// LLVM arguments and the types they were derived from.
  2182. ///
  2183. /// \param TargetDecl - If given, the decl of the function in a direct call;
  2184. /// used to set attributes on the call (noreturn, etc.).
  2185. RValue EmitCall(const CGFunctionInfo &FnInfo,
  2186. llvm::Value *Callee,
  2187. ReturnValueSlot ReturnValue,
  2188. const CallArgList &Args,
  2189. const Decl *TargetDecl = nullptr,
  2190. llvm::Instruction **callOrInvoke = nullptr);
  2191. RValue EmitCall(QualType FnType, llvm::Value *Callee, const CallExpr *E,
  2192. ReturnValueSlot ReturnValue,
  2193. const Decl *TargetDecl = nullptr,
  2194. llvm::Value *Chain = nullptr);
  2195. RValue EmitCallExpr(const CallExpr *E,
  2196. ReturnValueSlot ReturnValue = ReturnValueSlot());
  2197. llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
  2198. const Twine &name = "");
  2199. llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
  2200. ArrayRef<llvm::Value*> args,
  2201. const Twine &name = "");
  2202. llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
  2203. const Twine &name = "");
  2204. llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
  2205. ArrayRef<llvm::Value*> args,
  2206. const Twine &name = "");
  2207. llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
  2208. ArrayRef<llvm::Value *> Args,
  2209. const Twine &Name = "");
  2210. llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
  2211. const Twine &Name = "");
  2212. llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
  2213. ArrayRef<llvm::Value*> args,
  2214. const Twine &name = "");
  2215. llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
  2216. const Twine &name = "");
  2217. void EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
  2218. ArrayRef<llvm::Value*> args);
  2219. llvm::Value *BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
  2220. NestedNameSpecifier *Qual,
  2221. llvm::Type *Ty);
  2222. llvm::Value *BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD,
  2223. CXXDtorType Type,
  2224. const CXXRecordDecl *RD);
  2225. RValue
  2226. EmitCXXMemberOrOperatorCall(const CXXMethodDecl *MD, llvm::Value *Callee,
  2227. ReturnValueSlot ReturnValue, llvm::Value *This,
  2228. llvm::Value *ImplicitParam,
  2229. QualType ImplicitParamTy, const CallExpr *E);
  2230. RValue EmitCXXStructorCall(const CXXMethodDecl *MD, llvm::Value *Callee,
  2231. ReturnValueSlot ReturnValue, llvm::Value *This,
  2232. llvm::Value *ImplicitParam,
  2233. QualType ImplicitParamTy, const CallExpr *E,
  2234. StructorType Type);
  2235. RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
  2236. ReturnValueSlot ReturnValue);
  2237. RValue EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr *CE,
  2238. const CXXMethodDecl *MD,
  2239. ReturnValueSlot ReturnValue,
  2240. bool HasQualifier,
  2241. NestedNameSpecifier *Qualifier,
  2242. bool IsArrow, const Expr *Base);
  2243. // Compute the object pointer.
  2244. Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
  2245. llvm::Value *memberPtr,
  2246. const MemberPointerType *memberPtrType,
  2247. AlignmentSource *AlignSource = nullptr);
  2248. RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
  2249. ReturnValueSlot ReturnValue);
  2250. RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
  2251. const CXXMethodDecl *MD,
  2252. ReturnValueSlot ReturnValue);
  2253. RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
  2254. ReturnValueSlot ReturnValue);
  2255. RValue EmitBuiltinExpr(const FunctionDecl *FD,
  2256. unsigned BuiltinID, const CallExpr *E,
  2257. ReturnValueSlot ReturnValue);
  2258. RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
  2259. /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
  2260. /// is unhandled by the current target.
  2261. llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2262. llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty,
  2263. const llvm::CmpInst::Predicate Fp,
  2264. const llvm::CmpInst::Predicate Ip,
  2265. const llvm::Twine &Name = "");
  2266. llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2267. llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID,
  2268. unsigned LLVMIntrinsic,
  2269. unsigned AltLLVMIntrinsic,
  2270. const char *NameHint,
  2271. unsigned Modifier,
  2272. const CallExpr *E,
  2273. SmallVectorImpl<llvm::Value *> &Ops,
  2274. Address PtrOp0, Address PtrOp1);
  2275. llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID,
  2276. unsigned Modifier, llvm::Type *ArgTy,
  2277. const CallExpr *E);
  2278. llvm::Value *EmitNeonCall(llvm::Function *F,
  2279. SmallVectorImpl<llvm::Value*> &O,
  2280. const char *name,
  2281. unsigned shift = 0, bool rightshift = false);
  2282. llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
  2283. llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty,
  2284. bool negateForRightShift);
  2285. llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt,
  2286. llvm::Type *Ty, bool usgn, const char *name);
  2287. // Helper functions for EmitAArch64BuiltinExpr.
  2288. llvm::Value *vectorWrapScalar8(llvm::Value *Op);
  2289. llvm::Value *vectorWrapScalar16(llvm::Value *Op);
  2290. llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2291. llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops);
  2292. llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2293. llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2294. llvm::Value *EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2295. llvm::Value *EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2296. llvm::Value *EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2297. llvm::Value *EmitWebAssemblyBuiltinExpr(unsigned BuiltinID,
  2298. const CallExpr *E);
  2299. llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
  2300. llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
  2301. llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E);
  2302. llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E);
  2303. llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E);
  2304. llvm::Value *EmitObjCCollectionLiteral(const Expr *E,
  2305. const ObjCMethodDecl *MethodWithObjects);
  2306. llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
  2307. RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
  2308. ReturnValueSlot Return = ReturnValueSlot());
  2309. /// Retrieves the default cleanup kind for an ARC cleanup.
  2310. /// Except under -fobjc-arc-eh, ARC cleanups are normal-only.
  2311. CleanupKind getARCCleanupKind() {
  2312. return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions
  2313. ? NormalAndEHCleanup : NormalCleanup;
  2314. }
  2315. // ARC primitives.
  2316. void EmitARCInitWeak(Address addr, llvm::Value *value);
  2317. void EmitARCDestroyWeak(Address addr);
  2318. llvm::Value *EmitARCLoadWeak(Address addr);
  2319. llvm::Value *EmitARCLoadWeakRetained(Address addr);
  2320. llvm::Value *EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored);
  2321. void EmitARCCopyWeak(Address dst, Address src);
  2322. void EmitARCMoveWeak(Address dst, Address src);
  2323. llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value);
  2324. llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value);
  2325. llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value,
  2326. bool resultIgnored);
  2327. llvm::Value *EmitARCStoreStrongCall(Address addr, llvm::Value *value,
  2328. bool resultIgnored);
  2329. llvm::Value *EmitARCRetain(QualType type, llvm::Value *value);
  2330. llvm::Value *EmitARCRetainNonBlock(llvm::Value *value);
  2331. llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory);
  2332. void EmitARCDestroyStrong(Address addr, ARCPreciseLifetime_t precise);
  2333. void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
  2334. llvm::Value *EmitARCAutorelease(llvm::Value *value);
  2335. llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value);
  2336. llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value);
  2337. llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value);
  2338. std::pair<LValue,llvm::Value*>
  2339. EmitARCStoreAutoreleasing(const BinaryOperator *e);
  2340. std::pair<LValue,llvm::Value*>
  2341. EmitARCStoreStrong(const BinaryOperator *e, bool ignored);
  2342. llvm::Value *EmitObjCThrowOperand(const Expr *expr);
  2343. llvm::Value *EmitObjCProduceObject(QualType T, llvm::Value *Ptr);
  2344. llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr);
  2345. llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr);
  2346. llvm::Value *EmitARCExtendBlockObject(const Expr *expr);
  2347. llvm::Value *EmitARCRetainScalarExpr(const Expr *expr);
  2348. llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr);
  2349. void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values);
  2350. static Destroyer destroyARCStrongImprecise;
  2351. static Destroyer destroyARCStrongPrecise;
  2352. static Destroyer destroyARCWeak;
  2353. void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr);
  2354. llvm::Value *EmitObjCAutoreleasePoolPush();
  2355. llvm::Value *EmitObjCMRRAutoreleasePoolPush();
  2356. void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr);
  2357. void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr);
  2358. /// \brief Emits a reference binding to the passed in expression.
  2359. RValue EmitReferenceBindingToExpr(const Expr *E);
  2360. //===--------------------------------------------------------------------===//
  2361. // Expression Emission
  2362. //===--------------------------------------------------------------------===//
  2363. // Expressions are broken into three classes: scalar, complex, aggregate.
  2364. /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
  2365. /// scalar type, returning the result.
  2366. llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
  2367. /// Emit a conversion from the specified type to the specified destination
  2368. /// type, both of which are LLVM scalar types.
  2369. llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
  2370. QualType DstTy, SourceLocation Loc);
  2371. /// Emit a conversion from the specified complex type to the specified
  2372. /// destination type, where the destination type is an LLVM scalar type.
  2373. llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
  2374. QualType DstTy,
  2375. SourceLocation Loc);
  2376. /// EmitAggExpr - Emit the computation of the specified expression
  2377. /// of aggregate type. The result is computed into the given slot,
  2378. /// which may be null to indicate that the value is not needed.
  2379. void EmitAggExpr(const Expr *E, AggValueSlot AS);
  2380. /// EmitAggExprToLValue - Emit the computation of the specified expression of
  2381. /// aggregate type into a temporary LValue.
  2382. LValue EmitAggExprToLValue(const Expr *E);
  2383. /// EmitGCMemmoveCollectable - Emit special API for structs with object
  2384. /// pointers.
  2385. void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr,
  2386. QualType Ty);
  2387. /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
  2388. /// make sure it survives garbage collection until this point.
  2389. void EmitExtendGCLifetime(llvm::Value *object);
  2390. /// EmitComplexExpr - Emit the computation of the specified expression of
  2391. /// complex type, returning the result.
  2392. ComplexPairTy EmitComplexExpr(const Expr *E,
  2393. bool IgnoreReal = false,
  2394. bool IgnoreImag = false);
  2395. /// EmitComplexExprIntoLValue - Emit the given expression of complex
  2396. /// type and place its result into the specified l-value.
  2397. void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit);
  2398. /// EmitStoreOfComplex - Store a complex number into the specified l-value.
  2399. void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit);
  2400. /// EmitLoadOfComplex - Load a complex number from the specified l-value.
  2401. ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc);
  2402. Address emitAddrOfRealComponent(Address complex, QualType complexType);
  2403. Address emitAddrOfImagComponent(Address complex, QualType complexType);
  2404. /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
  2405. /// global variable that has already been created for it. If the initializer
  2406. /// has a different type than GV does, this may free GV and return a different
  2407. /// one. Otherwise it just returns GV.
  2408. llvm::GlobalVariable *
  2409. AddInitializerToStaticVarDecl(const VarDecl &D,
  2410. llvm::GlobalVariable *GV);
  2411. /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
  2412. /// variable with global storage.
  2413. void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr,
  2414. bool PerformInit);
  2415. llvm::Constant *createAtExitStub(const VarDecl &VD, llvm::Constant *Dtor,
  2416. llvm::Constant *Addr);
  2417. /// Call atexit() with a function that passes the given argument to
  2418. /// the given function.
  2419. void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::Constant *fn,
  2420. llvm::Constant *addr);
  2421. /// Emit code in this function to perform a guarded variable
  2422. /// initialization. Guarded initializations are used when it's not
  2423. /// possible to prove that an initialization will be done exactly
  2424. /// once, e.g. with a static local variable or a static data member
  2425. /// of a class template.
  2426. void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr,
  2427. bool PerformInit);
  2428. /// GenerateCXXGlobalInitFunc - Generates code for initializing global
  2429. /// variables.
  2430. void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
  2431. ArrayRef<llvm::Function *> CXXThreadLocals,
  2432. Address Guard = Address::invalid());
  2433. /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global
  2434. /// variables.
  2435. void GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
  2436. const std::vector<std::pair<llvm::WeakVH,
  2437. llvm::Constant*> > &DtorsAndObjects);
  2438. void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
  2439. const VarDecl *D,
  2440. llvm::GlobalVariable *Addr,
  2441. bool PerformInit);
  2442. void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
  2443. void EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp);
  2444. void enterFullExpression(const ExprWithCleanups *E) {
  2445. if (E->getNumObjects() == 0) return;
  2446. enterNonTrivialFullExpression(E);
  2447. }
  2448. void enterNonTrivialFullExpression(const ExprWithCleanups *E);
  2449. void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true);
  2450. void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest);
  2451. RValue EmitAtomicExpr(AtomicExpr *E, Address Dest = Address::invalid());
  2452. //===--------------------------------------------------------------------===//
  2453. // Annotations Emission
  2454. //===--------------------------------------------------------------------===//
  2455. /// Emit an annotation call (intrinsic or builtin).
  2456. llvm::Value *EmitAnnotationCall(llvm::Value *AnnotationFn,
  2457. llvm::Value *AnnotatedVal,
  2458. StringRef AnnotationStr,
  2459. SourceLocation Location);
  2460. /// Emit local annotations for the local variable V, declared by D.
  2461. void EmitVarAnnotations(const VarDecl *D, llvm::Value *V);
  2462. /// Emit field annotations for the given field & value. Returns the
  2463. /// annotation result.
  2464. Address EmitFieldAnnotations(const FieldDecl *D, Address V);
  2465. //===--------------------------------------------------------------------===//
  2466. // Internal Helpers
  2467. //===--------------------------------------------------------------------===//
  2468. /// ContainsLabel - Return true if the statement contains a label in it. If
  2469. /// this statement is not executed normally, it not containing a label means
  2470. /// that we can just remove the code.
  2471. static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
  2472. /// containsBreak - Return true if the statement contains a break out of it.
  2473. /// If the statement (recursively) contains a switch or loop with a break
  2474. /// inside of it, this is fine.
  2475. static bool containsBreak(const Stmt *S);
  2476. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  2477. /// to a constant, or if it does but contains a label, return false. If it
  2478. /// constant folds return true and set the boolean result in Result.
  2479. bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result);
  2480. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  2481. /// to a constant, or if it does but contains a label, return false. If it
  2482. /// constant folds return true and set the folded value.
  2483. bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result);
  2484. /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
  2485. /// if statement) to the specified blocks. Based on the condition, this might
  2486. /// try to simplify the codegen of the conditional based on the branch.
  2487. /// TrueCount should be the number of times we expect the condition to
  2488. /// evaluate to true based on PGO data.
  2489. void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
  2490. llvm::BasicBlock *FalseBlock, uint64_t TrueCount);
  2491. /// \brief Emit a description of a type in a format suitable for passing to
  2492. /// a runtime sanitizer handler.
  2493. llvm::Constant *EmitCheckTypeDescriptor(QualType T);
  2494. /// \brief Convert a value into a format suitable for passing to a runtime
  2495. /// sanitizer handler.
  2496. llvm::Value *EmitCheckValue(llvm::Value *V);
  2497. /// \brief Emit a description of a source location in a format suitable for
  2498. /// passing to a runtime sanitizer handler.
  2499. llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc);
  2500. /// \brief Create a basic block that will call a handler function in a
  2501. /// sanitizer runtime with the provided arguments, and create a conditional
  2502. /// branch to it.
  2503. void EmitCheck(ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
  2504. StringRef CheckName, ArrayRef<llvm::Constant *> StaticArgs,
  2505. ArrayRef<llvm::Value *> DynamicArgs);
  2506. /// \brief Create a basic block that will call the trap intrinsic, and emit a
  2507. /// conditional branch to it, for the -ftrapv checks.
  2508. void EmitTrapCheck(llvm::Value *Checked);
  2509. /// \brief Emit a call to trap or debugtrap and attach function attribute
  2510. /// "trap-func-name" if specified.
  2511. llvm::CallInst *EmitTrapCall(llvm::Intrinsic::ID IntrID);
  2512. /// \brief Create a check for a function parameter that may potentially be
  2513. /// declared as non-null.
  2514. void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc,
  2515. const FunctionDecl *FD, unsigned ParmNum);
  2516. /// EmitCallArg - Emit a single call argument.
  2517. void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType);
  2518. /// EmitDelegateCallArg - We are performing a delegate call; that
  2519. /// is, the current function is delegating to another one. Produce
  2520. /// a r-value suitable for passing the given parameter.
  2521. void EmitDelegateCallArg(CallArgList &args, const VarDecl *param,
  2522. SourceLocation loc);
  2523. /// SetFPAccuracy - Set the minimum required accuracy of the given floating
  2524. /// point operation, expressed as the maximum relative error in ulp.
  2525. void SetFPAccuracy(llvm::Value *Val, float Accuracy);
  2526. private:
  2527. llvm::MDNode *getRangeForLoadFromType(QualType Ty);
  2528. void EmitReturnOfRValue(RValue RV, QualType Ty);
  2529. void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New);
  2530. llvm::SmallVector<std::pair<llvm::Instruction *, llvm::Value *>, 4>
  2531. DeferredReplacements;
  2532. /// Set the address of a local variable.
  2533. void setAddrOfLocalVar(const VarDecl *VD, Address Addr) {
  2534. assert(!LocalDeclMap.count(VD) && "Decl already exists in LocalDeclMap!");
  2535. LocalDeclMap.insert({VD, Addr});
  2536. }
  2537. /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
  2538. /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
  2539. ///
  2540. /// \param AI - The first function argument of the expansion.
  2541. void ExpandTypeFromArgs(QualType Ty, LValue Dst,
  2542. SmallVectorImpl<llvm::Argument *>::iterator &AI);
  2543. /// ExpandTypeToArgs - Expand an RValue \arg RV, with the LLVM type for \arg
  2544. /// Ty, into individual arguments on the provided vector \arg IRCallArgs,
  2545. /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand.
  2546. void ExpandTypeToArgs(QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
  2547. SmallVectorImpl<llvm::Value *> &IRCallArgs,
  2548. unsigned &IRCallArgPos);
  2549. llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info,
  2550. const Expr *InputExpr, std::string &ConstraintStr);
  2551. llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
  2552. LValue InputValue, QualType InputType,
  2553. std::string &ConstraintStr,
  2554. SourceLocation Loc);
  2555. public:
  2556. #ifndef NDEBUG
  2557. // Determine whether the given argument is an Objective-C method
  2558. // that may have type parameters in its signature.
  2559. static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
  2560. const DeclContext *dc = method->getDeclContext();
  2561. if (const ObjCInterfaceDecl *classDecl= dyn_cast<ObjCInterfaceDecl>(dc)) {
  2562. return classDecl->getTypeParamListAsWritten();
  2563. }
  2564. if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
  2565. return catDecl->getTypeParamList();
  2566. }
  2567. return false;
  2568. }
  2569. template<typename T>
  2570. static bool isObjCMethodWithTypeParams(const T *) { return false; }
  2571. #endif
  2572. /// EmitCallArgs - Emit call arguments for a function.
  2573. template <typename T>
  2574. void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo,
  2575. llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
  2576. const FunctionDecl *CalleeDecl = nullptr,
  2577. unsigned ParamsToSkip = 0) {
  2578. SmallVector<QualType, 16> ArgTypes;
  2579. CallExpr::const_arg_iterator Arg = ArgRange.begin();
  2580. assert((ParamsToSkip == 0 || CallArgTypeInfo) &&
  2581. "Can't skip parameters if type info is not provided");
  2582. if (CallArgTypeInfo) {
  2583. #ifndef NDEBUG
  2584. bool isGenericMethod = isObjCMethodWithTypeParams(CallArgTypeInfo);
  2585. #endif
  2586. // First, use the argument types that the type info knows about
  2587. for (auto I = CallArgTypeInfo->param_type_begin() + ParamsToSkip,
  2588. E = CallArgTypeInfo->param_type_end();
  2589. I != E; ++I, ++Arg) {
  2590. assert(Arg != ArgRange.end() && "Running over edge of argument list!");
  2591. assert((isGenericMethod ||
  2592. ((*I)->isVariablyModifiedType() ||
  2593. (*I).getNonReferenceType()->isObjCRetainableType() ||
  2594. getContext()
  2595. .getCanonicalType((*I).getNonReferenceType())
  2596. .getTypePtr() ==
  2597. getContext()
  2598. .getCanonicalType((*Arg)->getType())
  2599. .getTypePtr())) &&
  2600. "type mismatch in call argument!");
  2601. ArgTypes.push_back(*I);
  2602. }
  2603. }
  2604. // Either we've emitted all the call args, or we have a call to variadic
  2605. // function.
  2606. assert((Arg == ArgRange.end() || !CallArgTypeInfo ||
  2607. CallArgTypeInfo->isVariadic()) &&
  2608. "Extra arguments in non-variadic function!");
  2609. // If we still have any arguments, emit them using the type of the argument.
  2610. for (auto *A : llvm::make_range(Arg, ArgRange.end()))
  2611. ArgTypes.push_back(getVarArgType(A));
  2612. EmitCallArgs(Args, ArgTypes, ArgRange, CalleeDecl, ParamsToSkip);
  2613. }
  2614. void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes,
  2615. llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
  2616. const FunctionDecl *CalleeDecl = nullptr,
  2617. unsigned ParamsToSkip = 0);
  2618. /// EmitPointerWithAlignment - Given an expression with a pointer
  2619. /// type, emit the value and compute our best estimate of the
  2620. /// alignment of the pointee.
  2621. ///
  2622. /// Note that this function will conservatively fall back on the type
  2623. /// when it doesn't
  2624. ///
  2625. /// \param Source - If non-null, this will be initialized with
  2626. /// information about the source of the alignment. Note that this
  2627. /// function will conservatively fall back on the type when it
  2628. /// doesn't recognize the expression, which means that sometimes
  2629. ///
  2630. /// a worst-case One
  2631. /// reasonable way to use this information is when there's a
  2632. /// language guarantee that the pointer must be aligned to some
  2633. /// stricter value, and we're simply trying to ensure that
  2634. /// sufficiently obvious uses of under-aligned objects don't get
  2635. /// miscompiled; for example, a placement new into the address of
  2636. /// a local variable. In such a case, it's quite reasonable to
  2637. /// just ignore the returned alignment when it isn't from an
  2638. /// explicit source.
  2639. Address EmitPointerWithAlignment(const Expr *Addr,
  2640. AlignmentSource *Source = nullptr);
  2641. private:
  2642. QualType getVarArgType(const Expr *Arg);
  2643. const TargetCodeGenInfo &getTargetHooks() const {
  2644. return CGM.getTargetCodeGenInfo();
  2645. }
  2646. void EmitDeclMetadata();
  2647. BlockByrefHelpers *buildByrefHelpers(llvm::StructType &byrefType,
  2648. const AutoVarEmission &emission);
  2649. void AddObjCARCExceptionMetadata(llvm::Instruction *Inst);
  2650. llvm::Value *GetValueForARMHint(unsigned BuiltinID);
  2651. };
  2652. /// Helper class with most of the code for saving a value for a
  2653. /// conditional expression cleanup.
  2654. struct DominatingLLVMValue {
  2655. typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
  2656. /// Answer whether the given value needs extra work to be saved.
  2657. static bool needsSaving(llvm::Value *value) {
  2658. // If it's not an instruction, we don't need to save.
  2659. if (!isa<llvm::Instruction>(value)) return false;
  2660. // If it's an instruction in the entry block, we don't need to save.
  2661. llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
  2662. return (block != &block->getParent()->getEntryBlock());
  2663. }
  2664. /// Try to save the given value.
  2665. static saved_type save(CodeGenFunction &CGF, llvm::Value *value) {
  2666. if (!needsSaving(value)) return saved_type(value, false);
  2667. // Otherwise, we need an alloca.
  2668. auto align = CharUnits::fromQuantity(
  2669. CGF.CGM.getDataLayout().getPrefTypeAlignment(value->getType()));
  2670. Address alloca =
  2671. CGF.CreateTempAlloca(value->getType(), align, "cond-cleanup.save");
  2672. CGF.Builder.CreateStore(value, alloca);
  2673. return saved_type(alloca.getPointer(), true);
  2674. }
  2675. static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) {
  2676. // If the value says it wasn't saved, trust that it's still dominating.
  2677. if (!value.getInt()) return value.getPointer();
  2678. // Otherwise, it should be an alloca instruction, as set up in save().
  2679. auto alloca = cast<llvm::AllocaInst>(value.getPointer());
  2680. return CGF.Builder.CreateAlignedLoad(alloca, alloca->getAlignment());
  2681. }
  2682. };
  2683. /// A partial specialization of DominatingValue for llvm::Values that
  2684. /// might be llvm::Instructions.
  2685. template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
  2686. typedef T *type;
  2687. static type restore(CodeGenFunction &CGF, saved_type value) {
  2688. return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
  2689. }
  2690. };
  2691. /// A specialization of DominatingValue for Address.
  2692. template <> struct DominatingValue<Address> {
  2693. typedef Address type;
  2694. struct saved_type {
  2695. DominatingLLVMValue::saved_type SavedValue;
  2696. CharUnits Alignment;
  2697. };
  2698. static bool needsSaving(type value) {
  2699. return DominatingLLVMValue::needsSaving(value.getPointer());
  2700. }
  2701. static saved_type save(CodeGenFunction &CGF, type value) {
  2702. return { DominatingLLVMValue::save(CGF, value.getPointer()),
  2703. value.getAlignment() };
  2704. }
  2705. static type restore(CodeGenFunction &CGF, saved_type value) {
  2706. return Address(DominatingLLVMValue::restore(CGF, value.SavedValue),
  2707. value.Alignment);
  2708. }
  2709. };
  2710. /// A specialization of DominatingValue for RValue.
  2711. template <> struct DominatingValue<RValue> {
  2712. typedef RValue type;
  2713. class saved_type {
  2714. enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
  2715. AggregateAddress, ComplexAddress };
  2716. llvm::Value *Value;
  2717. unsigned K : 3;
  2718. unsigned Align : 29;
  2719. saved_type(llvm::Value *v, Kind k, unsigned a = 0)
  2720. : Value(v), K(k), Align(a) {}
  2721. public:
  2722. static bool needsSaving(RValue value);
  2723. static saved_type save(CodeGenFunction &CGF, RValue value);
  2724. RValue restore(CodeGenFunction &CGF);
  2725. // implementations in CGCleanup.cpp
  2726. };
  2727. static bool needsSaving(type value) {
  2728. return saved_type::needsSaving(value);
  2729. }
  2730. static saved_type save(CodeGenFunction &CGF, type value) {
  2731. return saved_type::save(CGF, value);
  2732. }
  2733. static type restore(CodeGenFunction &CGF, saved_type value) {
  2734. return value.restore(CGF);
  2735. }
  2736. };
  2737. } // end namespace CodeGen
  2738. } // end namespace clang
  2739. #endif