CodeGenFunction.h 112 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777
  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 CLANG_CODEGEN_CODEGENFUNCTION_H
  14. #define CLANG_CODEGEN_CODEGENFUNCTION_H
  15. #include "CGBuilder.h"
  16. #include "CGDebugInfo.h"
  17. #include "CGValue.h"
  18. #include "CodeGenModule.h"
  19. #include "clang/AST/CharUnits.h"
  20. #include "clang/AST/ExprCXX.h"
  21. #include "clang/AST/ExprObjC.h"
  22. #include "clang/AST/Type.h"
  23. #include "clang/Basic/ABI.h"
  24. #include "clang/Basic/TargetInfo.h"
  25. #include "clang/Frontend/CodeGenOptions.h"
  26. #include "llvm/ADT/ArrayRef.h"
  27. #include "llvm/ADT/DenseMap.h"
  28. #include "llvm/ADT/SmallVector.h"
  29. #include "llvm/Support/Debug.h"
  30. #include "llvm/Support/ValueHandle.h"
  31. namespace llvm {
  32. class BasicBlock;
  33. class LLVMContext;
  34. class MDNode;
  35. class Module;
  36. class SwitchInst;
  37. class Twine;
  38. class Value;
  39. class CallSite;
  40. }
  41. namespace clang {
  42. class ASTContext;
  43. class BlockDecl;
  44. class CXXDestructorDecl;
  45. class CXXForRangeStmt;
  46. class CXXTryStmt;
  47. class Decl;
  48. class LabelDecl;
  49. class EnumConstantDecl;
  50. class FunctionDecl;
  51. class FunctionProtoType;
  52. class LabelStmt;
  53. class ObjCContainerDecl;
  54. class ObjCInterfaceDecl;
  55. class ObjCIvarDecl;
  56. class ObjCMethodDecl;
  57. class ObjCImplementationDecl;
  58. class ObjCPropertyImplDecl;
  59. class TargetInfo;
  60. class TargetCodeGenInfo;
  61. class VarDecl;
  62. class ObjCForCollectionStmt;
  63. class ObjCAtTryStmt;
  64. class ObjCAtThrowStmt;
  65. class ObjCAtSynchronizedStmt;
  66. class ObjCAutoreleasePoolStmt;
  67. namespace CodeGen {
  68. class CodeGenTypes;
  69. class CGFunctionInfo;
  70. class CGRecordLayout;
  71. class CGBlockInfo;
  72. class CGCXXABI;
  73. class BlockFlags;
  74. class BlockFieldFlags;
  75. /// A branch fixup. These are required when emitting a goto to a
  76. /// label which hasn't been emitted yet. The goto is optimistically
  77. /// emitted as a branch to the basic block for the label, and (if it
  78. /// occurs in a scope with non-trivial cleanups) a fixup is added to
  79. /// the innermost cleanup. When a (normal) cleanup is popped, any
  80. /// unresolved fixups in that scope are threaded through the cleanup.
  81. struct BranchFixup {
  82. /// The block containing the terminator which needs to be modified
  83. /// into a switch if this fixup is resolved into the current scope.
  84. /// If null, LatestBranch points directly to the destination.
  85. llvm::BasicBlock *OptimisticBranchBlock;
  86. /// The ultimate destination of the branch.
  87. ///
  88. /// This can be set to null to indicate that this fixup was
  89. /// successfully resolved.
  90. llvm::BasicBlock *Destination;
  91. /// The destination index value.
  92. unsigned DestinationIndex;
  93. /// The initial branch of the fixup.
  94. llvm::BranchInst *InitialBranch;
  95. };
  96. template <class T> struct InvariantValue {
  97. typedef T type;
  98. typedef T saved_type;
  99. static bool needsSaving(type value) { return false; }
  100. static saved_type save(CodeGenFunction &CGF, type value) { return value; }
  101. static type restore(CodeGenFunction &CGF, saved_type value) { return value; }
  102. };
  103. /// A metaprogramming class for ensuring that a value will dominate an
  104. /// arbitrary position in a function.
  105. template <class T> struct DominatingValue : InvariantValue<T> {};
  106. template <class T, bool mightBeInstruction =
  107. llvm::is_base_of<llvm::Value, T>::value &&
  108. !llvm::is_base_of<llvm::Constant, T>::value &&
  109. !llvm::is_base_of<llvm::BasicBlock, T>::value>
  110. struct DominatingPointer;
  111. template <class T> struct DominatingPointer<T,false> : InvariantValue<T*> {};
  112. // template <class T> struct DominatingPointer<T,true> at end of file
  113. template <class T> struct DominatingValue<T*> : DominatingPointer<T> {};
  114. enum CleanupKind {
  115. EHCleanup = 0x1,
  116. NormalCleanup = 0x2,
  117. NormalAndEHCleanup = EHCleanup | NormalCleanup,
  118. InactiveCleanup = 0x4,
  119. InactiveEHCleanup = EHCleanup | InactiveCleanup,
  120. InactiveNormalCleanup = NormalCleanup | InactiveCleanup,
  121. InactiveNormalAndEHCleanup = NormalAndEHCleanup | InactiveCleanup
  122. };
  123. /// A stack of scopes which respond to exceptions, including cleanups
  124. /// and catch blocks.
  125. class EHScopeStack {
  126. public:
  127. /// A saved depth on the scope stack. This is necessary because
  128. /// pushing scopes onto the stack invalidates iterators.
  129. class stable_iterator {
  130. friend class EHScopeStack;
  131. /// Offset from StartOfData to EndOfBuffer.
  132. ptrdiff_t Size;
  133. stable_iterator(ptrdiff_t Size) : Size(Size) {}
  134. public:
  135. static stable_iterator invalid() { return stable_iterator(-1); }
  136. stable_iterator() : Size(-1) {}
  137. bool isValid() const { return Size >= 0; }
  138. /// Returns true if this scope encloses I.
  139. /// Returns false if I is invalid.
  140. /// This scope must be valid.
  141. bool encloses(stable_iterator I) const { return Size <= I.Size; }
  142. /// Returns true if this scope strictly encloses I: that is,
  143. /// if it encloses I and is not I.
  144. /// Returns false is I is invalid.
  145. /// This scope must be valid.
  146. bool strictlyEncloses(stable_iterator I) const { return Size < I.Size; }
  147. friend bool operator==(stable_iterator A, stable_iterator B) {
  148. return A.Size == B.Size;
  149. }
  150. friend bool operator!=(stable_iterator A, stable_iterator B) {
  151. return A.Size != B.Size;
  152. }
  153. };
  154. /// Information for lazily generating a cleanup. Subclasses must be
  155. /// POD-like: cleanups will not be destructed, and they will be
  156. /// allocated on the cleanup stack and freely copied and moved
  157. /// around.
  158. ///
  159. /// Cleanup implementations should generally be declared in an
  160. /// anonymous namespace.
  161. class Cleanup {
  162. // Anchor the construction vtable.
  163. virtual void anchor();
  164. public:
  165. /// Generation flags.
  166. class Flags {
  167. enum {
  168. F_IsForEH = 0x1,
  169. F_IsNormalCleanupKind = 0x2,
  170. F_IsEHCleanupKind = 0x4
  171. };
  172. unsigned flags;
  173. public:
  174. Flags() : flags(0) {}
  175. /// isForEH - true if the current emission is for an EH cleanup.
  176. bool isForEHCleanup() const { return flags & F_IsForEH; }
  177. bool isForNormalCleanup() const { return !isForEHCleanup(); }
  178. void setIsForEHCleanup() { flags |= F_IsForEH; }
  179. bool isNormalCleanupKind() const { return flags & F_IsNormalCleanupKind; }
  180. void setIsNormalCleanupKind() { flags |= F_IsNormalCleanupKind; }
  181. /// isEHCleanupKind - true if the cleanup was pushed as an EH
  182. /// cleanup.
  183. bool isEHCleanupKind() const { return flags & F_IsEHCleanupKind; }
  184. void setIsEHCleanupKind() { flags |= F_IsEHCleanupKind; }
  185. };
  186. // Provide a virtual destructor to suppress a very common warning
  187. // that unfortunately cannot be suppressed without this. Cleanups
  188. // should not rely on this destructor ever being called.
  189. virtual ~Cleanup() {}
  190. /// Emit the cleanup. For normal cleanups, this is run in the
  191. /// same EH context as when the cleanup was pushed, i.e. the
  192. /// immediately-enclosing context of the cleanup scope. For
  193. /// EH cleanups, this is run in a terminate context.
  194. ///
  195. // \param flags cleanup kind.
  196. virtual void Emit(CodeGenFunction &CGF, Flags flags) = 0;
  197. };
  198. /// ConditionalCleanupN stores the saved form of its N parameters,
  199. /// then restores them and performs the cleanup.
  200. template <class T, class A0>
  201. class ConditionalCleanup1 : public Cleanup {
  202. typedef typename DominatingValue<A0>::saved_type A0_saved;
  203. A0_saved a0_saved;
  204. void Emit(CodeGenFunction &CGF, Flags flags) {
  205. A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved);
  206. T(a0).Emit(CGF, flags);
  207. }
  208. public:
  209. ConditionalCleanup1(A0_saved a0)
  210. : a0_saved(a0) {}
  211. };
  212. template <class T, class A0, class A1>
  213. class ConditionalCleanup2 : public Cleanup {
  214. typedef typename DominatingValue<A0>::saved_type A0_saved;
  215. typedef typename DominatingValue<A1>::saved_type A1_saved;
  216. A0_saved a0_saved;
  217. A1_saved a1_saved;
  218. void Emit(CodeGenFunction &CGF, Flags flags) {
  219. A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved);
  220. A1 a1 = DominatingValue<A1>::restore(CGF, a1_saved);
  221. T(a0, a1).Emit(CGF, flags);
  222. }
  223. public:
  224. ConditionalCleanup2(A0_saved a0, A1_saved a1)
  225. : a0_saved(a0), a1_saved(a1) {}
  226. };
  227. template <class T, class A0, class A1, class A2>
  228. class ConditionalCleanup3 : public Cleanup {
  229. typedef typename DominatingValue<A0>::saved_type A0_saved;
  230. typedef typename DominatingValue<A1>::saved_type A1_saved;
  231. typedef typename DominatingValue<A2>::saved_type A2_saved;
  232. A0_saved a0_saved;
  233. A1_saved a1_saved;
  234. A2_saved a2_saved;
  235. void Emit(CodeGenFunction &CGF, Flags flags) {
  236. A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved);
  237. A1 a1 = DominatingValue<A1>::restore(CGF, a1_saved);
  238. A2 a2 = DominatingValue<A2>::restore(CGF, a2_saved);
  239. T(a0, a1, a2).Emit(CGF, flags);
  240. }
  241. public:
  242. ConditionalCleanup3(A0_saved a0, A1_saved a1, A2_saved a2)
  243. : a0_saved(a0), a1_saved(a1), a2_saved(a2) {}
  244. };
  245. template <class T, class A0, class A1, class A2, class A3>
  246. class ConditionalCleanup4 : public Cleanup {
  247. typedef typename DominatingValue<A0>::saved_type A0_saved;
  248. typedef typename DominatingValue<A1>::saved_type A1_saved;
  249. typedef typename DominatingValue<A2>::saved_type A2_saved;
  250. typedef typename DominatingValue<A3>::saved_type A3_saved;
  251. A0_saved a0_saved;
  252. A1_saved a1_saved;
  253. A2_saved a2_saved;
  254. A3_saved a3_saved;
  255. void Emit(CodeGenFunction &CGF, Flags flags) {
  256. A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved);
  257. A1 a1 = DominatingValue<A1>::restore(CGF, a1_saved);
  258. A2 a2 = DominatingValue<A2>::restore(CGF, a2_saved);
  259. A3 a3 = DominatingValue<A3>::restore(CGF, a3_saved);
  260. T(a0, a1, a2, a3).Emit(CGF, flags);
  261. }
  262. public:
  263. ConditionalCleanup4(A0_saved a0, A1_saved a1, A2_saved a2, A3_saved a3)
  264. : a0_saved(a0), a1_saved(a1), a2_saved(a2), a3_saved(a3) {}
  265. };
  266. private:
  267. // The implementation for this class is in CGException.h and
  268. // CGException.cpp; the definition is here because it's used as a
  269. // member of CodeGenFunction.
  270. /// The start of the scope-stack buffer, i.e. the allocated pointer
  271. /// for the buffer. All of these pointers are either simultaneously
  272. /// null or simultaneously valid.
  273. char *StartOfBuffer;
  274. /// The end of the buffer.
  275. char *EndOfBuffer;
  276. /// The first valid entry in the buffer.
  277. char *StartOfData;
  278. /// The innermost normal cleanup on the stack.
  279. stable_iterator InnermostNormalCleanup;
  280. /// The innermost EH scope on the stack.
  281. stable_iterator InnermostEHScope;
  282. /// The current set of branch fixups. A branch fixup is a jump to
  283. /// an as-yet unemitted label, i.e. a label for which we don't yet
  284. /// know the EH stack depth. Whenever we pop a cleanup, we have
  285. /// to thread all the current branch fixups through it.
  286. ///
  287. /// Fixups are recorded as the Use of the respective branch or
  288. /// switch statement. The use points to the final destination.
  289. /// When popping out of a cleanup, these uses are threaded through
  290. /// the cleanup and adjusted to point to the new cleanup.
  291. ///
  292. /// Note that branches are allowed to jump into protected scopes
  293. /// in certain situations; e.g. the following code is legal:
  294. /// struct A { ~A(); }; // trivial ctor, non-trivial dtor
  295. /// goto foo;
  296. /// A a;
  297. /// foo:
  298. /// bar();
  299. SmallVector<BranchFixup, 8> BranchFixups;
  300. char *allocate(size_t Size);
  301. void *pushCleanup(CleanupKind K, size_t DataSize);
  302. public:
  303. EHScopeStack() : StartOfBuffer(0), EndOfBuffer(0), StartOfData(0),
  304. InnermostNormalCleanup(stable_end()),
  305. InnermostEHScope(stable_end()) {}
  306. ~EHScopeStack() { delete[] StartOfBuffer; }
  307. // Variadic templates would make this not terrible.
  308. /// Push a lazily-created cleanup on the stack.
  309. template <class T>
  310. void pushCleanup(CleanupKind Kind) {
  311. void *Buffer = pushCleanup(Kind, sizeof(T));
  312. Cleanup *Obj = new(Buffer) T();
  313. (void) Obj;
  314. }
  315. /// Push a lazily-created cleanup on the stack.
  316. template <class T, class A0>
  317. void pushCleanup(CleanupKind Kind, A0 a0) {
  318. void *Buffer = pushCleanup(Kind, sizeof(T));
  319. Cleanup *Obj = new(Buffer) T(a0);
  320. (void) Obj;
  321. }
  322. /// Push a lazily-created cleanup on the stack.
  323. template <class T, class A0, class A1>
  324. void pushCleanup(CleanupKind Kind, A0 a0, A1 a1) {
  325. void *Buffer = pushCleanup(Kind, sizeof(T));
  326. Cleanup *Obj = new(Buffer) T(a0, a1);
  327. (void) Obj;
  328. }
  329. /// Push a lazily-created cleanup on the stack.
  330. template <class T, class A0, class A1, class A2>
  331. void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2) {
  332. void *Buffer = pushCleanup(Kind, sizeof(T));
  333. Cleanup *Obj = new(Buffer) T(a0, a1, a2);
  334. (void) Obj;
  335. }
  336. /// Push a lazily-created cleanup on the stack.
  337. template <class T, class A0, class A1, class A2, class A3>
  338. void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3) {
  339. void *Buffer = pushCleanup(Kind, sizeof(T));
  340. Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3);
  341. (void) Obj;
  342. }
  343. /// Push a lazily-created cleanup on the stack.
  344. template <class T, class A0, class A1, class A2, class A3, class A4>
  345. void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) {
  346. void *Buffer = pushCleanup(Kind, sizeof(T));
  347. Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3, a4);
  348. (void) Obj;
  349. }
  350. // Feel free to add more variants of the following:
  351. /// Push a cleanup with non-constant storage requirements on the
  352. /// stack. The cleanup type must provide an additional static method:
  353. /// static size_t getExtraSize(size_t);
  354. /// The argument to this method will be the value N, which will also
  355. /// be passed as the first argument to the constructor.
  356. ///
  357. /// The data stored in the extra storage must obey the same
  358. /// restrictions as normal cleanup member data.
  359. ///
  360. /// The pointer returned from this method is valid until the cleanup
  361. /// stack is modified.
  362. template <class T, class A0, class A1, class A2>
  363. T *pushCleanupWithExtra(CleanupKind Kind, size_t N, A0 a0, A1 a1, A2 a2) {
  364. void *Buffer = pushCleanup(Kind, sizeof(T) + T::getExtraSize(N));
  365. return new (Buffer) T(N, a0, a1, a2);
  366. }
  367. /// Pops a cleanup scope off the stack. This is private to CGCleanup.cpp.
  368. void popCleanup();
  369. /// Push a set of catch handlers on the stack. The catch is
  370. /// uninitialized and will need to have the given number of handlers
  371. /// set on it.
  372. class EHCatchScope *pushCatch(unsigned NumHandlers);
  373. /// Pops a catch scope off the stack. This is private to CGException.cpp.
  374. void popCatch();
  375. /// Push an exceptions filter on the stack.
  376. class EHFilterScope *pushFilter(unsigned NumFilters);
  377. /// Pops an exceptions filter off the stack.
  378. void popFilter();
  379. /// Push a terminate handler on the stack.
  380. void pushTerminate();
  381. /// Pops a terminate handler off the stack.
  382. void popTerminate();
  383. /// Determines whether the exception-scopes stack is empty.
  384. bool empty() const { return StartOfData == EndOfBuffer; }
  385. bool requiresLandingPad() const {
  386. return InnermostEHScope != stable_end();
  387. }
  388. /// Determines whether there are any normal cleanups on the stack.
  389. bool hasNormalCleanups() const {
  390. return InnermostNormalCleanup != stable_end();
  391. }
  392. /// Returns the innermost normal cleanup on the stack, or
  393. /// stable_end() if there are no normal cleanups.
  394. stable_iterator getInnermostNormalCleanup() const {
  395. return InnermostNormalCleanup;
  396. }
  397. stable_iterator getInnermostActiveNormalCleanup() const;
  398. stable_iterator getInnermostEHScope() const {
  399. return InnermostEHScope;
  400. }
  401. stable_iterator getInnermostActiveEHScope() const;
  402. /// An unstable reference to a scope-stack depth. Invalidated by
  403. /// pushes but not pops.
  404. class iterator;
  405. /// Returns an iterator pointing to the innermost EH scope.
  406. iterator begin() const;
  407. /// Returns an iterator pointing to the outermost EH scope.
  408. iterator end() const;
  409. /// Create a stable reference to the top of the EH stack. The
  410. /// returned reference is valid until that scope is popped off the
  411. /// stack.
  412. stable_iterator stable_begin() const {
  413. return stable_iterator(EndOfBuffer - StartOfData);
  414. }
  415. /// Create a stable reference to the bottom of the EH stack.
  416. static stable_iterator stable_end() {
  417. return stable_iterator(0);
  418. }
  419. /// Translates an iterator into a stable_iterator.
  420. stable_iterator stabilize(iterator it) const;
  421. /// Turn a stable reference to a scope depth into a unstable pointer
  422. /// to the EH stack.
  423. iterator find(stable_iterator save) const;
  424. /// Removes the cleanup pointed to by the given stable_iterator.
  425. void removeCleanup(stable_iterator save);
  426. /// Add a branch fixup to the current cleanup scope.
  427. BranchFixup &addBranchFixup() {
  428. assert(hasNormalCleanups() && "adding fixup in scope without cleanups");
  429. BranchFixups.push_back(BranchFixup());
  430. return BranchFixups.back();
  431. }
  432. unsigned getNumBranchFixups() const { return BranchFixups.size(); }
  433. BranchFixup &getBranchFixup(unsigned I) {
  434. assert(I < getNumBranchFixups());
  435. return BranchFixups[I];
  436. }
  437. /// Pops lazily-removed fixups from the end of the list. This
  438. /// should only be called by procedures which have just popped a
  439. /// cleanup or resolved one or more fixups.
  440. void popNullFixups();
  441. /// Clears the branch-fixups list. This should only be called by
  442. /// ResolveAllBranchFixups.
  443. void clearFixups() { BranchFixups.clear(); }
  444. };
  445. /// CodeGenFunction - This class organizes the per-function state that is used
  446. /// while generating LLVM code.
  447. class CodeGenFunction : public CodeGenTypeCache {
  448. CodeGenFunction(const CodeGenFunction &) LLVM_DELETED_FUNCTION;
  449. void operator=(const CodeGenFunction &) LLVM_DELETED_FUNCTION;
  450. friend class CGCXXABI;
  451. public:
  452. /// A jump destination is an abstract label, branching to which may
  453. /// require a jump out through normal cleanups.
  454. struct JumpDest {
  455. JumpDest() : Block(0), ScopeDepth(), Index(0) {}
  456. JumpDest(llvm::BasicBlock *Block,
  457. EHScopeStack::stable_iterator Depth,
  458. unsigned Index)
  459. : Block(Block), ScopeDepth(Depth), Index(Index) {}
  460. bool isValid() const { return Block != 0; }
  461. llvm::BasicBlock *getBlock() const { return Block; }
  462. EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
  463. unsigned getDestIndex() const { return Index; }
  464. private:
  465. llvm::BasicBlock *Block;
  466. EHScopeStack::stable_iterator ScopeDepth;
  467. unsigned Index;
  468. };
  469. CodeGenModule &CGM; // Per-module state.
  470. const TargetInfo &Target;
  471. typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
  472. CGBuilderTy Builder;
  473. /// CurFuncDecl - Holds the Decl for the current function or ObjC method.
  474. /// This excludes BlockDecls.
  475. const Decl *CurFuncDecl;
  476. /// CurCodeDecl - This is the inner-most code context, which includes blocks.
  477. const Decl *CurCodeDecl;
  478. const CGFunctionInfo *CurFnInfo;
  479. QualType FnRetTy;
  480. llvm::Function *CurFn;
  481. /// CurGD - The GlobalDecl for the current function being compiled.
  482. GlobalDecl CurGD;
  483. /// PrologueCleanupDepth - The cleanup depth enclosing all the
  484. /// cleanups associated with the parameters.
  485. EHScopeStack::stable_iterator PrologueCleanupDepth;
  486. /// ReturnBlock - Unified return block.
  487. JumpDest ReturnBlock;
  488. /// ReturnValue - The temporary alloca to hold the return value. This is null
  489. /// iff the function has no return value.
  490. llvm::Value *ReturnValue;
  491. /// AllocaInsertPoint - This is an instruction in the entry block before which
  492. /// we prefer to insert allocas.
  493. llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
  494. /// BoundsChecking - Emit run-time bounds checks. Higher values mean
  495. /// potentially higher performance penalties.
  496. unsigned char BoundsChecking;
  497. /// \brief Whether any type-checking sanitizers are enabled. If \c false,
  498. /// calls to EmitTypeCheck can be skipped.
  499. bool SanitizePerformTypeCheck;
  500. /// In ARC, whether we should autorelease the return value.
  501. bool AutoreleaseResult;
  502. const CodeGen::CGBlockInfo *BlockInfo;
  503. llvm::Value *BlockPointer;
  504. llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
  505. FieldDecl *LambdaThisCaptureField;
  506. /// \brief A mapping from NRVO variables to the flags used to indicate
  507. /// when the NRVO has been applied to this variable.
  508. llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
  509. EHScopeStack EHStack;
  510. /// i32s containing the indexes of the cleanup destinations.
  511. llvm::AllocaInst *NormalCleanupDest;
  512. unsigned NextCleanupDestIndex;
  513. /// FirstBlockInfo - The head of a singly-linked-list of block layouts.
  514. CGBlockInfo *FirstBlockInfo;
  515. /// EHResumeBlock - Unified block containing a call to llvm.eh.resume.
  516. llvm::BasicBlock *EHResumeBlock;
  517. /// The exception slot. All landing pads write the current exception pointer
  518. /// into this alloca.
  519. llvm::Value *ExceptionSlot;
  520. /// The selector slot. Under the MandatoryCleanup model, all landing pads
  521. /// write the current selector value into this alloca.
  522. llvm::AllocaInst *EHSelectorSlot;
  523. /// Emits a landing pad for the current EH stack.
  524. llvm::BasicBlock *EmitLandingPad();
  525. llvm::BasicBlock *getInvokeDestImpl();
  526. template <class T>
  527. typename DominatingValue<T>::saved_type saveValueInCond(T value) {
  528. return DominatingValue<T>::save(*this, value);
  529. }
  530. public:
  531. /// ObjCEHValueStack - Stack of Objective-C exception values, used for
  532. /// rethrows.
  533. SmallVector<llvm::Value*, 8> ObjCEHValueStack;
  534. /// A class controlling the emission of a finally block.
  535. class FinallyInfo {
  536. /// Where the catchall's edge through the cleanup should go.
  537. JumpDest RethrowDest;
  538. /// A function to call to enter the catch.
  539. llvm::Constant *BeginCatchFn;
  540. /// An i1 variable indicating whether or not the @finally is
  541. /// running for an exception.
  542. llvm::AllocaInst *ForEHVar;
  543. /// An i8* variable into which the exception pointer to rethrow
  544. /// has been saved.
  545. llvm::AllocaInst *SavedExnVar;
  546. public:
  547. void enter(CodeGenFunction &CGF, const Stmt *Finally,
  548. llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn,
  549. llvm::Constant *rethrowFn);
  550. void exit(CodeGenFunction &CGF);
  551. };
  552. /// pushFullExprCleanup - Push a cleanup to be run at the end of the
  553. /// current full-expression. Safe against the possibility that
  554. /// we're currently inside a conditionally-evaluated expression.
  555. template <class T, class A0>
  556. void pushFullExprCleanup(CleanupKind kind, A0 a0) {
  557. // If we're not in a conditional branch, or if none of the
  558. // arguments requires saving, then use the unconditional cleanup.
  559. if (!isInConditionalBranch())
  560. return EHStack.pushCleanup<T>(kind, a0);
  561. typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0);
  562. typedef EHScopeStack::ConditionalCleanup1<T, A0> CleanupType;
  563. EHStack.pushCleanup<CleanupType>(kind, a0_saved);
  564. initFullExprCleanup();
  565. }
  566. /// pushFullExprCleanup - Push a cleanup to be run at the end of the
  567. /// current full-expression. Safe against the possibility that
  568. /// we're currently inside a conditionally-evaluated expression.
  569. template <class T, class A0, class A1>
  570. void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1) {
  571. // If we're not in a conditional branch, or if none of the
  572. // arguments requires saving, then use the unconditional cleanup.
  573. if (!isInConditionalBranch())
  574. return EHStack.pushCleanup<T>(kind, a0, a1);
  575. typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0);
  576. typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1);
  577. typedef EHScopeStack::ConditionalCleanup2<T, A0, A1> CleanupType;
  578. EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved);
  579. initFullExprCleanup();
  580. }
  581. /// pushFullExprCleanup - Push a cleanup to be run at the end of the
  582. /// current full-expression. Safe against the possibility that
  583. /// we're currently inside a conditionally-evaluated expression.
  584. template <class T, class A0, class A1, class A2>
  585. void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1, A2 a2) {
  586. // If we're not in a conditional branch, or if none of the
  587. // arguments requires saving, then use the unconditional cleanup.
  588. if (!isInConditionalBranch()) {
  589. return EHStack.pushCleanup<T>(kind, a0, a1, a2);
  590. }
  591. typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0);
  592. typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1);
  593. typename DominatingValue<A2>::saved_type a2_saved = saveValueInCond(a2);
  594. typedef EHScopeStack::ConditionalCleanup3<T, A0, A1, A2> CleanupType;
  595. EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved, a2_saved);
  596. initFullExprCleanup();
  597. }
  598. /// pushFullExprCleanup - Push a cleanup to be run at the end of the
  599. /// current full-expression. Safe against the possibility that
  600. /// we're currently inside a conditionally-evaluated expression.
  601. template <class T, class A0, class A1, class A2, class A3>
  602. void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1, A2 a2, A3 a3) {
  603. // If we're not in a conditional branch, or if none of the
  604. // arguments requires saving, then use the unconditional cleanup.
  605. if (!isInConditionalBranch()) {
  606. return EHStack.pushCleanup<T>(kind, a0, a1, a2, a3);
  607. }
  608. typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0);
  609. typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1);
  610. typename DominatingValue<A2>::saved_type a2_saved = saveValueInCond(a2);
  611. typename DominatingValue<A3>::saved_type a3_saved = saveValueInCond(a3);
  612. typedef EHScopeStack::ConditionalCleanup4<T, A0, A1, A2, A3> CleanupType;
  613. EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved,
  614. a2_saved, a3_saved);
  615. initFullExprCleanup();
  616. }
  617. /// Set up the last cleaup that was pushed as a conditional
  618. /// full-expression cleanup.
  619. void initFullExprCleanup();
  620. /// PushDestructorCleanup - Push a cleanup to call the
  621. /// complete-object destructor of an object of the given type at the
  622. /// given address. Does nothing if T is not a C++ class type with a
  623. /// non-trivial destructor.
  624. void PushDestructorCleanup(QualType T, llvm::Value *Addr);
  625. /// PushDestructorCleanup - Push a cleanup to call the
  626. /// complete-object variant of the given destructor on the object at
  627. /// the given address.
  628. void PushDestructorCleanup(const CXXDestructorDecl *Dtor,
  629. llvm::Value *Addr);
  630. /// PopCleanupBlock - Will pop the cleanup entry on the stack and
  631. /// process all branch fixups.
  632. void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
  633. /// DeactivateCleanupBlock - Deactivates the given cleanup block.
  634. /// The block cannot be reactivated. Pops it if it's the top of the
  635. /// stack.
  636. ///
  637. /// \param DominatingIP - An instruction which is known to
  638. /// dominate the current IP (if set) and which lies along
  639. /// all paths of execution between the current IP and the
  640. /// the point at which the cleanup comes into scope.
  641. void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
  642. llvm::Instruction *DominatingIP);
  643. /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
  644. /// Cannot be used to resurrect a deactivated cleanup.
  645. ///
  646. /// \param DominatingIP - An instruction which is known to
  647. /// dominate the current IP (if set) and which lies along
  648. /// all paths of execution between the current IP and the
  649. /// the point at which the cleanup comes into scope.
  650. void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
  651. llvm::Instruction *DominatingIP);
  652. /// \brief Enters a new scope for capturing cleanups, all of which
  653. /// will be executed once the scope is exited.
  654. class RunCleanupsScope {
  655. EHScopeStack::stable_iterator CleanupStackDepth;
  656. bool OldDidCallStackSave;
  657. bool PerformCleanup;
  658. RunCleanupsScope(const RunCleanupsScope &) LLVM_DELETED_FUNCTION;
  659. void operator=(const RunCleanupsScope &) LLVM_DELETED_FUNCTION;
  660. protected:
  661. CodeGenFunction& CGF;
  662. public:
  663. /// \brief Enter a new cleanup scope.
  664. explicit RunCleanupsScope(CodeGenFunction &CGF)
  665. : PerformCleanup(true), CGF(CGF)
  666. {
  667. CleanupStackDepth = CGF.EHStack.stable_begin();
  668. OldDidCallStackSave = CGF.DidCallStackSave;
  669. CGF.DidCallStackSave = false;
  670. }
  671. /// \brief Exit this cleanup scope, emitting any accumulated
  672. /// cleanups.
  673. ~RunCleanupsScope() {
  674. if (PerformCleanup) {
  675. CGF.DidCallStackSave = OldDidCallStackSave;
  676. CGF.PopCleanupBlocks(CleanupStackDepth);
  677. }
  678. }
  679. /// \brief Determine whether this scope requires any cleanups.
  680. bool requiresCleanups() const {
  681. return CGF.EHStack.stable_begin() != CleanupStackDepth;
  682. }
  683. /// \brief Force the emission of cleanups now, instead of waiting
  684. /// until this object is destroyed.
  685. void ForceCleanup() {
  686. assert(PerformCleanup && "Already forced cleanup");
  687. CGF.DidCallStackSave = OldDidCallStackSave;
  688. CGF.PopCleanupBlocks(CleanupStackDepth);
  689. PerformCleanup = false;
  690. }
  691. };
  692. class LexicalScope: protected RunCleanupsScope {
  693. SourceRange Range;
  694. bool PopDebugStack;
  695. LexicalScope(const LexicalScope &) LLVM_DELETED_FUNCTION;
  696. void operator=(const LexicalScope &) LLVM_DELETED_FUNCTION;
  697. public:
  698. /// \brief Enter a new cleanup scope.
  699. explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range)
  700. : RunCleanupsScope(CGF), Range(Range), PopDebugStack(true) {
  701. if (CGDebugInfo *DI = CGF.getDebugInfo())
  702. DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin());
  703. }
  704. /// \brief Exit this cleanup scope, emitting any accumulated
  705. /// cleanups.
  706. ~LexicalScope() {
  707. if (PopDebugStack) {
  708. CGDebugInfo *DI = CGF.getDebugInfo();
  709. if (DI) DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
  710. }
  711. }
  712. /// \brief Force the emission of cleanups now, instead of waiting
  713. /// until this object is destroyed.
  714. void ForceCleanup() {
  715. RunCleanupsScope::ForceCleanup();
  716. if (CGDebugInfo *DI = CGF.getDebugInfo()) {
  717. DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
  718. PopDebugStack = false;
  719. }
  720. }
  721. };
  722. /// PopCleanupBlocks - Takes the old cleanup stack size and emits
  723. /// the cleanup blocks that have been added.
  724. void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize);
  725. void ResolveBranchFixups(llvm::BasicBlock *Target);
  726. /// The given basic block lies in the current EH scope, but may be a
  727. /// target of a potentially scope-crossing jump; get a stable handle
  728. /// to which we can perform this jump later.
  729. JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
  730. return JumpDest(Target,
  731. EHStack.getInnermostNormalCleanup(),
  732. NextCleanupDestIndex++);
  733. }
  734. /// The given basic block lies in the current EH scope, but may be a
  735. /// target of a potentially scope-crossing jump; get a stable handle
  736. /// to which we can perform this jump later.
  737. JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) {
  738. return getJumpDestInCurrentScope(createBasicBlock(Name));
  739. }
  740. /// EmitBranchThroughCleanup - Emit a branch from the current insert
  741. /// block through the normal cleanup handling code (if any) and then
  742. /// on to \arg Dest.
  743. void EmitBranchThroughCleanup(JumpDest Dest);
  744. /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
  745. /// specified destination obviously has no cleanups to run. 'false' is always
  746. /// a conservatively correct answer for this method.
  747. bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const;
  748. /// popCatchScope - Pops the catch scope at the top of the EHScope
  749. /// stack, emitting any required code (other than the catch handlers
  750. /// themselves).
  751. void popCatchScope();
  752. llvm::BasicBlock *getEHResumeBlock(bool isCleanup);
  753. llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope);
  754. /// An object to manage conditionally-evaluated expressions.
  755. class ConditionalEvaluation {
  756. llvm::BasicBlock *StartBB;
  757. public:
  758. ConditionalEvaluation(CodeGenFunction &CGF)
  759. : StartBB(CGF.Builder.GetInsertBlock()) {}
  760. void begin(CodeGenFunction &CGF) {
  761. assert(CGF.OutermostConditional != this);
  762. if (!CGF.OutermostConditional)
  763. CGF.OutermostConditional = this;
  764. }
  765. void end(CodeGenFunction &CGF) {
  766. assert(CGF.OutermostConditional != 0);
  767. if (CGF.OutermostConditional == this)
  768. CGF.OutermostConditional = 0;
  769. }
  770. /// Returns a block which will be executed prior to each
  771. /// evaluation of the conditional code.
  772. llvm::BasicBlock *getStartingBlock() const {
  773. return StartBB;
  774. }
  775. };
  776. /// isInConditionalBranch - Return true if we're currently emitting
  777. /// one branch or the other of a conditional expression.
  778. bool isInConditionalBranch() const { return OutermostConditional != 0; }
  779. void setBeforeOutermostConditional(llvm::Value *value, llvm::Value *addr) {
  780. assert(isInConditionalBranch());
  781. llvm::BasicBlock *block = OutermostConditional->getStartingBlock();
  782. new llvm::StoreInst(value, addr, &block->back());
  783. }
  784. /// An RAII object to record that we're evaluating a statement
  785. /// expression.
  786. class StmtExprEvaluation {
  787. CodeGenFunction &CGF;
  788. /// We have to save the outermost conditional: cleanups in a
  789. /// statement expression aren't conditional just because the
  790. /// StmtExpr is.
  791. ConditionalEvaluation *SavedOutermostConditional;
  792. public:
  793. StmtExprEvaluation(CodeGenFunction &CGF)
  794. : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) {
  795. CGF.OutermostConditional = 0;
  796. }
  797. ~StmtExprEvaluation() {
  798. CGF.OutermostConditional = SavedOutermostConditional;
  799. CGF.EnsureInsertPoint();
  800. }
  801. };
  802. /// An object which temporarily prevents a value from being
  803. /// destroyed by aggressive peephole optimizations that assume that
  804. /// all uses of a value have been realized in the IR.
  805. class PeepholeProtection {
  806. llvm::Instruction *Inst;
  807. friend class CodeGenFunction;
  808. public:
  809. PeepholeProtection() : Inst(0) {}
  810. };
  811. /// A non-RAII class containing all the information about a bound
  812. /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for
  813. /// this which makes individual mappings very simple; using this
  814. /// class directly is useful when you have a variable number of
  815. /// opaque values or don't want the RAII functionality for some
  816. /// reason.
  817. class OpaqueValueMappingData {
  818. const OpaqueValueExpr *OpaqueValue;
  819. bool BoundLValue;
  820. CodeGenFunction::PeepholeProtection Protection;
  821. OpaqueValueMappingData(const OpaqueValueExpr *ov,
  822. bool boundLValue)
  823. : OpaqueValue(ov), BoundLValue(boundLValue) {}
  824. public:
  825. OpaqueValueMappingData() : OpaqueValue(0) {}
  826. static bool shouldBindAsLValue(const Expr *expr) {
  827. // gl-values should be bound as l-values for obvious reasons.
  828. // Records should be bound as l-values because IR generation
  829. // always keeps them in memory. Expressions of function type
  830. // act exactly like l-values but are formally required to be
  831. // r-values in C.
  832. return expr->isGLValue() ||
  833. expr->getType()->isRecordType() ||
  834. expr->getType()->isFunctionType();
  835. }
  836. static OpaqueValueMappingData bind(CodeGenFunction &CGF,
  837. const OpaqueValueExpr *ov,
  838. const Expr *e) {
  839. if (shouldBindAsLValue(ov))
  840. return bind(CGF, ov, CGF.EmitLValue(e));
  841. return bind(CGF, ov, CGF.EmitAnyExpr(e));
  842. }
  843. static OpaqueValueMappingData bind(CodeGenFunction &CGF,
  844. const OpaqueValueExpr *ov,
  845. const LValue &lv) {
  846. assert(shouldBindAsLValue(ov));
  847. CGF.OpaqueLValues.insert(std::make_pair(ov, lv));
  848. return OpaqueValueMappingData(ov, true);
  849. }
  850. static OpaqueValueMappingData bind(CodeGenFunction &CGF,
  851. const OpaqueValueExpr *ov,
  852. const RValue &rv) {
  853. assert(!shouldBindAsLValue(ov));
  854. CGF.OpaqueRValues.insert(std::make_pair(ov, rv));
  855. OpaqueValueMappingData data(ov, false);
  856. // Work around an extremely aggressive peephole optimization in
  857. // EmitScalarConversion which assumes that all other uses of a
  858. // value are extant.
  859. data.Protection = CGF.protectFromPeepholes(rv);
  860. return data;
  861. }
  862. bool isValid() const { return OpaqueValue != 0; }
  863. void clear() { OpaqueValue = 0; }
  864. void unbind(CodeGenFunction &CGF) {
  865. assert(OpaqueValue && "no data to unbind!");
  866. if (BoundLValue) {
  867. CGF.OpaqueLValues.erase(OpaqueValue);
  868. } else {
  869. CGF.OpaqueRValues.erase(OpaqueValue);
  870. CGF.unprotectFromPeepholes(Protection);
  871. }
  872. }
  873. };
  874. /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
  875. class OpaqueValueMapping {
  876. CodeGenFunction &CGF;
  877. OpaqueValueMappingData Data;
  878. public:
  879. static bool shouldBindAsLValue(const Expr *expr) {
  880. return OpaqueValueMappingData::shouldBindAsLValue(expr);
  881. }
  882. /// Build the opaque value mapping for the given conditional
  883. /// operator if it's the GNU ?: extension. This is a common
  884. /// enough pattern that the convenience operator is really
  885. /// helpful.
  886. ///
  887. OpaqueValueMapping(CodeGenFunction &CGF,
  888. const AbstractConditionalOperator *op) : CGF(CGF) {
  889. if (isa<ConditionalOperator>(op))
  890. // Leave Data empty.
  891. return;
  892. const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op);
  893. Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(),
  894. e->getCommon());
  895. }
  896. OpaqueValueMapping(CodeGenFunction &CGF,
  897. const OpaqueValueExpr *opaqueValue,
  898. LValue lvalue)
  899. : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) {
  900. }
  901. OpaqueValueMapping(CodeGenFunction &CGF,
  902. const OpaqueValueExpr *opaqueValue,
  903. RValue rvalue)
  904. : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) {
  905. }
  906. void pop() {
  907. Data.unbind(CGF);
  908. Data.clear();
  909. }
  910. ~OpaqueValueMapping() {
  911. if (Data.isValid()) Data.unbind(CGF);
  912. }
  913. };
  914. /// getByrefValueFieldNumber - Given a declaration, returns the LLVM field
  915. /// number that holds the value.
  916. unsigned getByRefValueLLVMField(const ValueDecl *VD) const;
  917. /// BuildBlockByrefAddress - Computes address location of the
  918. /// variable which is declared as __block.
  919. llvm::Value *BuildBlockByrefAddress(llvm::Value *BaseAddr,
  920. const VarDecl *V);
  921. private:
  922. CGDebugInfo *DebugInfo;
  923. bool DisableDebugInfo;
  924. /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
  925. /// calling llvm.stacksave for multiple VLAs in the same scope.
  926. bool DidCallStackSave;
  927. /// IndirectBranch - The first time an indirect goto is seen we create a block
  928. /// with an indirect branch. Every time we see the address of a label taken,
  929. /// we add the label to the indirect goto. Every subsequent indirect goto is
  930. /// codegen'd as a jump to the IndirectBranch's basic block.
  931. llvm::IndirectBrInst *IndirectBranch;
  932. /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
  933. /// decls.
  934. typedef llvm::DenseMap<const Decl*, llvm::Value*> DeclMapTy;
  935. DeclMapTy LocalDeclMap;
  936. /// LabelMap - This keeps track of the LLVM basic block for each C label.
  937. llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap;
  938. // BreakContinueStack - This keeps track of where break and continue
  939. // statements should jump to.
  940. struct BreakContinue {
  941. BreakContinue(JumpDest Break, JumpDest Continue)
  942. : BreakBlock(Break), ContinueBlock(Continue) {}
  943. JumpDest BreakBlock;
  944. JumpDest ContinueBlock;
  945. };
  946. SmallVector<BreakContinue, 8> BreakContinueStack;
  947. /// SwitchInsn - This is nearest current switch instruction. It is null if
  948. /// current context is not in a switch.
  949. llvm::SwitchInst *SwitchInsn;
  950. /// CaseRangeBlock - This block holds if condition check for last case
  951. /// statement range in current switch instruction.
  952. llvm::BasicBlock *CaseRangeBlock;
  953. /// OpaqueLValues - Keeps track of the current set of opaque value
  954. /// expressions.
  955. llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
  956. llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
  957. // VLASizeMap - This keeps track of the associated size for each VLA type.
  958. // We track this by the size expression rather than the type itself because
  959. // in certain situations, like a const qualifier applied to an VLA typedef,
  960. // multiple VLA types can share the same size expression.
  961. // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
  962. // enter/leave scopes.
  963. llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
  964. /// A block containing a single 'unreachable' instruction. Created
  965. /// lazily by getUnreachableBlock().
  966. llvm::BasicBlock *UnreachableBlock;
  967. /// CXXThisDecl - When generating code for a C++ member function,
  968. /// this will hold the implicit 'this' declaration.
  969. ImplicitParamDecl *CXXABIThisDecl;
  970. llvm::Value *CXXABIThisValue;
  971. llvm::Value *CXXThisValue;
  972. /// CXXVTTDecl - When generating code for a base object constructor or
  973. /// base object destructor with virtual bases, this will hold the implicit
  974. /// VTT parameter.
  975. ImplicitParamDecl *CXXVTTDecl;
  976. llvm::Value *CXXVTTValue;
  977. /// OutermostConditional - Points to the outermost active
  978. /// conditional control. This is used so that we know if a
  979. /// temporary should be destroyed conditionally.
  980. ConditionalEvaluation *OutermostConditional;
  981. /// ByrefValueInfoMap - For each __block variable, contains a pair of the LLVM
  982. /// type as well as the field number that contains the actual data.
  983. llvm::DenseMap<const ValueDecl *, std::pair<llvm::Type *,
  984. unsigned> > ByRefValueInfo;
  985. llvm::BasicBlock *TerminateLandingPad;
  986. llvm::BasicBlock *TerminateHandler;
  987. llvm::BasicBlock *TrapBB;
  988. /// Add a kernel metadata node to the named metadata node 'opencl.kernels'.
  989. /// In the kernel metadata node, reference the kernel function and metadata
  990. /// nodes for its optional attribute qualifiers (OpenCL 1.1 6.7.2):
  991. /// - A node for the work_group_size_hint(X,Y,Z) qualifier contains string
  992. /// "work_group_size_hint", and three 32-bit integers X, Y and Z.
  993. /// - A node for the reqd_work_group_size(X,Y,Z) qualifier contains string
  994. /// "reqd_work_group_size", and three 32-bit integers X, Y and Z.
  995. void EmitOpenCLKernelMetadata(const FunctionDecl *FD,
  996. llvm::Function *Fn);
  997. public:
  998. CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false);
  999. ~CodeGenFunction();
  1000. CodeGenTypes &getTypes() const { return CGM.getTypes(); }
  1001. ASTContext &getContext() const { return CGM.getContext(); }
  1002. /// Returns true if DebugInfo is actually initialized.
  1003. bool maybeInitializeDebugInfo() {
  1004. if (CGM.getModuleDebugInfo()) {
  1005. DebugInfo = CGM.getModuleDebugInfo();
  1006. return true;
  1007. }
  1008. return false;
  1009. }
  1010. CGDebugInfo *getDebugInfo() {
  1011. if (DisableDebugInfo)
  1012. return NULL;
  1013. return DebugInfo;
  1014. }
  1015. void disableDebugInfo() { DisableDebugInfo = true; }
  1016. void enableDebugInfo() { DisableDebugInfo = false; }
  1017. bool shouldUseFusedARCCalls() {
  1018. return CGM.getCodeGenOpts().OptimizationLevel == 0;
  1019. }
  1020. const LangOptions &getLangOpts() const { return CGM.getLangOpts(); }
  1021. /// Returns a pointer to the function's exception object and selector slot,
  1022. /// which is assigned in every landing pad.
  1023. llvm::Value *getExceptionSlot();
  1024. llvm::Value *getEHSelectorSlot();
  1025. /// Returns the contents of the function's exception object and selector
  1026. /// slots.
  1027. llvm::Value *getExceptionFromSlot();
  1028. llvm::Value *getSelectorFromSlot();
  1029. llvm::Value *getNormalCleanupDestSlot();
  1030. llvm::BasicBlock *getUnreachableBlock() {
  1031. if (!UnreachableBlock) {
  1032. UnreachableBlock = createBasicBlock("unreachable");
  1033. new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
  1034. }
  1035. return UnreachableBlock;
  1036. }
  1037. llvm::BasicBlock *getInvokeDest() {
  1038. if (!EHStack.requiresLandingPad()) return 0;
  1039. return getInvokeDestImpl();
  1040. }
  1041. llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
  1042. //===--------------------------------------------------------------------===//
  1043. // Cleanups
  1044. //===--------------------------------------------------------------------===//
  1045. typedef void Destroyer(CodeGenFunction &CGF, llvm::Value *addr, QualType ty);
  1046. void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
  1047. llvm::Value *arrayEndPointer,
  1048. QualType elementType,
  1049. Destroyer *destroyer);
  1050. void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
  1051. llvm::Value *arrayEnd,
  1052. QualType elementType,
  1053. Destroyer *destroyer);
  1054. void pushDestroy(QualType::DestructionKind dtorKind,
  1055. llvm::Value *addr, QualType type);
  1056. void pushDestroy(CleanupKind kind, llvm::Value *addr, QualType type,
  1057. Destroyer *destroyer, bool useEHCleanupForArray);
  1058. void emitDestroy(llvm::Value *addr, QualType type, Destroyer *destroyer,
  1059. bool useEHCleanupForArray);
  1060. llvm::Function *generateDestroyHelper(llvm::Constant *addr,
  1061. QualType type,
  1062. Destroyer *destroyer,
  1063. bool useEHCleanupForArray);
  1064. void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
  1065. QualType type, Destroyer *destroyer,
  1066. bool checkZeroLength, bool useEHCleanup);
  1067. Destroyer *getDestroyer(QualType::DestructionKind destructionKind);
  1068. /// Determines whether an EH cleanup is required to destroy a type
  1069. /// with the given destruction kind.
  1070. bool needsEHCleanup(QualType::DestructionKind kind) {
  1071. switch (kind) {
  1072. case QualType::DK_none:
  1073. return false;
  1074. case QualType::DK_cxx_destructor:
  1075. case QualType::DK_objc_weak_lifetime:
  1076. return getLangOpts().Exceptions;
  1077. case QualType::DK_objc_strong_lifetime:
  1078. return getLangOpts().Exceptions &&
  1079. CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
  1080. }
  1081. llvm_unreachable("bad destruction kind");
  1082. }
  1083. CleanupKind getCleanupKind(QualType::DestructionKind kind) {
  1084. return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup);
  1085. }
  1086. //===--------------------------------------------------------------------===//
  1087. // Objective-C
  1088. //===--------------------------------------------------------------------===//
  1089. void GenerateObjCMethod(const ObjCMethodDecl *OMD);
  1090. void StartObjCMethod(const ObjCMethodDecl *MD,
  1091. const ObjCContainerDecl *CD,
  1092. SourceLocation StartLoc);
  1093. /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
  1094. void GenerateObjCGetter(ObjCImplementationDecl *IMP,
  1095. const ObjCPropertyImplDecl *PID);
  1096. void generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
  1097. const ObjCPropertyImplDecl *propImpl,
  1098. const ObjCMethodDecl *GetterMothodDecl,
  1099. llvm::Constant *AtomicHelperFn);
  1100. void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
  1101. ObjCMethodDecl *MD, bool ctor);
  1102. /// GenerateObjCSetter - Synthesize an Objective-C property setter function
  1103. /// for the given property.
  1104. void GenerateObjCSetter(ObjCImplementationDecl *IMP,
  1105. const ObjCPropertyImplDecl *PID);
  1106. void generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
  1107. const ObjCPropertyImplDecl *propImpl,
  1108. llvm::Constant *AtomicHelperFn);
  1109. bool IndirectObjCSetterArg(const CGFunctionInfo &FI);
  1110. bool IvarTypeWithAggrGCObjects(QualType Ty);
  1111. //===--------------------------------------------------------------------===//
  1112. // Block Bits
  1113. //===--------------------------------------------------------------------===//
  1114. llvm::Value *EmitBlockLiteral(const BlockExpr *);
  1115. llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info);
  1116. static void destroyBlockInfos(CGBlockInfo *info);
  1117. llvm::Constant *BuildDescriptorBlockDecl(const BlockExpr *,
  1118. const CGBlockInfo &Info,
  1119. llvm::StructType *,
  1120. llvm::Constant *BlockVarLayout);
  1121. llvm::Function *GenerateBlockFunction(GlobalDecl GD,
  1122. const CGBlockInfo &Info,
  1123. const Decl *OuterFuncDecl,
  1124. const DeclMapTy &ldm,
  1125. bool IsLambdaConversionToBlock);
  1126. llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
  1127. llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
  1128. llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction(
  1129. const ObjCPropertyImplDecl *PID);
  1130. llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction(
  1131. const ObjCPropertyImplDecl *PID);
  1132. llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty);
  1133. void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags);
  1134. class AutoVarEmission;
  1135. void emitByrefStructureInit(const AutoVarEmission &emission);
  1136. void enterByrefCleanup(const AutoVarEmission &emission);
  1137. llvm::Value *LoadBlockStruct() {
  1138. assert(BlockPointer && "no block pointer set!");
  1139. return BlockPointer;
  1140. }
  1141. void AllocateBlockCXXThisPointer(const CXXThisExpr *E);
  1142. void AllocateBlockDecl(const DeclRefExpr *E);
  1143. llvm::Value *GetAddrOfBlockDecl(const VarDecl *var, bool ByRef);
  1144. llvm::Type *BuildByRefType(const VarDecl *var);
  1145. void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
  1146. const CGFunctionInfo &FnInfo);
  1147. void StartFunction(GlobalDecl GD, QualType RetTy,
  1148. llvm::Function *Fn,
  1149. const CGFunctionInfo &FnInfo,
  1150. const FunctionArgList &Args,
  1151. SourceLocation StartLoc);
  1152. void EmitConstructorBody(FunctionArgList &Args);
  1153. void EmitDestructorBody(FunctionArgList &Args);
  1154. void EmitFunctionBody(FunctionArgList &Args);
  1155. void EmitForwardingCallToLambda(const CXXRecordDecl *Lambda,
  1156. CallArgList &CallArgs);
  1157. void EmitLambdaToBlockPointerBody(FunctionArgList &Args);
  1158. void EmitLambdaBlockInvokeBody();
  1159. void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD);
  1160. void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD);
  1161. /// EmitReturnBlock - Emit the unified return block, trying to avoid its
  1162. /// emission when possible.
  1163. void EmitReturnBlock();
  1164. /// FinishFunction - Complete IR generation of the current function. It is
  1165. /// legal to call this function even if there is no current insertion point.
  1166. void FinishFunction(SourceLocation EndLoc=SourceLocation());
  1167. /// GenerateThunk - Generate a thunk for the given method.
  1168. void GenerateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
  1169. GlobalDecl GD, const ThunkInfo &Thunk);
  1170. void GenerateVarArgsThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
  1171. GlobalDecl GD, const ThunkInfo &Thunk);
  1172. void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
  1173. FunctionArgList &Args);
  1174. void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init,
  1175. ArrayRef<VarDecl *> ArrayIndexes);
  1176. /// InitializeVTablePointer - Initialize the vtable pointer of the given
  1177. /// subobject.
  1178. ///
  1179. void InitializeVTablePointer(BaseSubobject Base,
  1180. const CXXRecordDecl *NearestVBase,
  1181. CharUnits OffsetFromNearestVBase,
  1182. llvm::Constant *VTable,
  1183. const CXXRecordDecl *VTableClass);
  1184. typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
  1185. void InitializeVTablePointers(BaseSubobject Base,
  1186. const CXXRecordDecl *NearestVBase,
  1187. CharUnits OffsetFromNearestVBase,
  1188. bool BaseIsNonVirtualPrimaryBase,
  1189. llvm::Constant *VTable,
  1190. const CXXRecordDecl *VTableClass,
  1191. VisitedVirtualBasesSetTy& VBases);
  1192. void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
  1193. /// GetVTablePtr - Return the Value of the vtable pointer member pointed
  1194. /// to by This.
  1195. llvm::Value *GetVTablePtr(llvm::Value *This, llvm::Type *Ty);
  1196. /// EnterDtorCleanups - Enter the cleanups necessary to complete the
  1197. /// given phase of destruction for a destructor. The end result
  1198. /// should call destructors on members and base classes in reverse
  1199. /// order of their construction.
  1200. void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
  1201. /// ShouldInstrumentFunction - Return true if the current function should be
  1202. /// instrumented with __cyg_profile_func_* calls
  1203. bool ShouldInstrumentFunction();
  1204. /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
  1205. /// instrumentation function with the current function and the call site, if
  1206. /// function instrumentation is enabled.
  1207. void EmitFunctionInstrumentation(const char *Fn);
  1208. /// EmitMCountInstrumentation - Emit call to .mcount.
  1209. void EmitMCountInstrumentation();
  1210. /// EmitFunctionProlog - Emit the target specific LLVM code to load the
  1211. /// arguments for the given function. This is also responsible for naming the
  1212. /// LLVM function arguments.
  1213. void EmitFunctionProlog(const CGFunctionInfo &FI,
  1214. llvm::Function *Fn,
  1215. const FunctionArgList &Args);
  1216. /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
  1217. /// given temporary.
  1218. void EmitFunctionEpilog(const CGFunctionInfo &FI);
  1219. /// EmitStartEHSpec - Emit the start of the exception spec.
  1220. void EmitStartEHSpec(const Decl *D);
  1221. /// EmitEndEHSpec - Emit the end of the exception spec.
  1222. void EmitEndEHSpec(const Decl *D);
  1223. /// getTerminateLandingPad - Return a landing pad that just calls terminate.
  1224. llvm::BasicBlock *getTerminateLandingPad();
  1225. /// getTerminateHandler - Return a handler (not a landing pad, just
  1226. /// a catch handler) that just calls terminate. This is used when
  1227. /// a terminate scope encloses a try.
  1228. llvm::BasicBlock *getTerminateHandler();
  1229. llvm::Type *ConvertTypeForMem(QualType T);
  1230. llvm::Type *ConvertType(QualType T);
  1231. llvm::Type *ConvertType(const TypeDecl *T) {
  1232. return ConvertType(getContext().getTypeDeclType(T));
  1233. }
  1234. /// LoadObjCSelf - Load the value of self. This function is only valid while
  1235. /// generating code for an Objective-C method.
  1236. llvm::Value *LoadObjCSelf();
  1237. /// TypeOfSelfObject - Return type of object that this self represents.
  1238. QualType TypeOfSelfObject();
  1239. /// hasAggregateLLVMType - Return true if the specified AST type will map into
  1240. /// an aggregate LLVM type or is void.
  1241. static bool hasAggregateLLVMType(QualType T);
  1242. /// createBasicBlock - Create an LLVM basic block.
  1243. llvm::BasicBlock *createBasicBlock(const Twine &name = "",
  1244. llvm::Function *parent = 0,
  1245. llvm::BasicBlock *before = 0) {
  1246. #ifdef NDEBUG
  1247. return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before);
  1248. #else
  1249. return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
  1250. #endif
  1251. }
  1252. /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
  1253. /// label maps to.
  1254. JumpDest getJumpDestForLabel(const LabelDecl *S);
  1255. /// SimplifyForwardingBlocks - If the given basic block is only a branch to
  1256. /// another basic block, simplify it. This assumes that no other code could
  1257. /// potentially reference the basic block.
  1258. void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
  1259. /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
  1260. /// adding a fall-through branch from the current insert block if
  1261. /// necessary. It is legal to call this function even if there is no current
  1262. /// insertion point.
  1263. ///
  1264. /// IsFinished - If true, indicates that the caller has finished emitting
  1265. /// branches to the given block and does not expect to emit code into it. This
  1266. /// means the block can be ignored if it is unreachable.
  1267. void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
  1268. /// EmitBlockAfterUses - Emit the given block somewhere hopefully
  1269. /// near its uses, and leave the insertion point in it.
  1270. void EmitBlockAfterUses(llvm::BasicBlock *BB);
  1271. /// EmitBranch - Emit a branch to the specified basic block from the current
  1272. /// insert block, taking care to avoid creation of branches from dummy
  1273. /// blocks. It is legal to call this function even if there is no current
  1274. /// insertion point.
  1275. ///
  1276. /// This function clears the current insertion point. The caller should follow
  1277. /// calls to this function with calls to Emit*Block prior to generation new
  1278. /// code.
  1279. void EmitBranch(llvm::BasicBlock *Block);
  1280. /// HaveInsertPoint - True if an insertion point is defined. If not, this
  1281. /// indicates that the current code being emitted is unreachable.
  1282. bool HaveInsertPoint() const {
  1283. return Builder.GetInsertBlock() != 0;
  1284. }
  1285. /// EnsureInsertPoint - Ensure that an insertion point is defined so that
  1286. /// emitted IR has a place to go. Note that by definition, if this function
  1287. /// creates a block then that block is unreachable; callers may do better to
  1288. /// detect when no insertion point is defined and simply skip IR generation.
  1289. void EnsureInsertPoint() {
  1290. if (!HaveInsertPoint())
  1291. EmitBlock(createBasicBlock());
  1292. }
  1293. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  1294. /// specified stmt yet.
  1295. void ErrorUnsupported(const Stmt *S, const char *Type,
  1296. bool OmitOnError=false);
  1297. //===--------------------------------------------------------------------===//
  1298. // Helpers
  1299. //===--------------------------------------------------------------------===//
  1300. LValue MakeAddrLValue(llvm::Value *V, QualType T,
  1301. CharUnits Alignment = CharUnits()) {
  1302. return LValue::MakeAddr(V, T, Alignment, getContext(),
  1303. CGM.getTBAAInfo(T));
  1304. }
  1305. LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
  1306. CharUnits Alignment;
  1307. if (!T->isIncompleteType())
  1308. Alignment = getContext().getTypeAlignInChars(T);
  1309. return LValue::MakeAddr(V, T, Alignment, getContext(),
  1310. CGM.getTBAAInfo(T));
  1311. }
  1312. /// CreateTempAlloca - This creates a alloca and inserts it into the entry
  1313. /// block. The caller is responsible for setting an appropriate alignment on
  1314. /// the alloca.
  1315. llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty,
  1316. const Twine &Name = "tmp");
  1317. /// InitTempAlloca - Provide an initial value for the given alloca.
  1318. void InitTempAlloca(llvm::AllocaInst *Alloca, llvm::Value *Value);
  1319. /// CreateIRTemp - Create a temporary IR object of the given type, with
  1320. /// appropriate alignment. This routine should only be used when an temporary
  1321. /// value needs to be stored into an alloca (for example, to avoid explicit
  1322. /// PHI construction), but the type is the IR type, not the type appropriate
  1323. /// for storing in memory.
  1324. llvm::AllocaInst *CreateIRTemp(QualType T, const Twine &Name = "tmp");
  1325. /// CreateMemTemp - Create a temporary memory object of the given type, with
  1326. /// appropriate alignment.
  1327. llvm::AllocaInst *CreateMemTemp(QualType T, const Twine &Name = "tmp");
  1328. /// CreateAggTemp - Create a temporary memory object for the given
  1329. /// aggregate type.
  1330. AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") {
  1331. CharUnits Alignment = getContext().getTypeAlignInChars(T);
  1332. return AggValueSlot::forAddr(CreateMemTemp(T, Name), Alignment,
  1333. T.getQualifiers(),
  1334. AggValueSlot::IsNotDestructed,
  1335. AggValueSlot::DoesNotNeedGCBarriers,
  1336. AggValueSlot::IsNotAliased);
  1337. }
  1338. /// Emit a cast to void* in the appropriate address space.
  1339. llvm::Value *EmitCastToVoidPtr(llvm::Value *value);
  1340. /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
  1341. /// expression and compare the result against zero, returning an Int1Ty value.
  1342. llvm::Value *EvaluateExprAsBool(const Expr *E);
  1343. /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
  1344. void EmitIgnoredExpr(const Expr *E);
  1345. /// EmitAnyExpr - Emit code to compute the specified expression which can have
  1346. /// any type. The result is returned as an RValue struct. If this is an
  1347. /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
  1348. /// the result should be returned.
  1349. ///
  1350. /// \param ignoreResult True if the resulting value isn't used.
  1351. RValue EmitAnyExpr(const Expr *E,
  1352. AggValueSlot aggSlot = AggValueSlot::ignored(),
  1353. bool ignoreResult = false);
  1354. // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
  1355. // or the value of the expression, depending on how va_list is defined.
  1356. llvm::Value *EmitVAListRef(const Expr *E);
  1357. /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
  1358. /// always be accessible even if no aggregate location is provided.
  1359. RValue EmitAnyExprToTemp(const Expr *E);
  1360. /// EmitAnyExprToMem - Emits the code necessary to evaluate an
  1361. /// arbitrary expression into the given memory location.
  1362. void EmitAnyExprToMem(const Expr *E, llvm::Value *Location,
  1363. Qualifiers Quals, bool IsInitializer);
  1364. /// EmitExprAsInit - Emits the code necessary to initialize a
  1365. /// location in memory with the given initializer.
  1366. void EmitExprAsInit(const Expr *init, const ValueDecl *D,
  1367. LValue lvalue, bool capturedByInit);
  1368. /// EmitAggregateCopy - Emit an aggrate assignment.
  1369. ///
  1370. /// The difference to EmitAggregateCopy is that tail padding is not copied.
  1371. /// This is required for correctness when assigning non-POD structures in C++.
  1372. void EmitAggregateAssign(llvm::Value *DestPtr, llvm::Value *SrcPtr,
  1373. QualType EltTy, bool isVolatile=false,
  1374. CharUnits Alignment = CharUnits::Zero()) {
  1375. EmitAggregateCopy(DestPtr, SrcPtr, EltTy, isVolatile, Alignment, true);
  1376. }
  1377. /// EmitAggregateCopy - Emit an aggrate copy.
  1378. ///
  1379. /// \param isVolatile - True iff either the source or the destination is
  1380. /// volatile.
  1381. /// \param isAssignment - If false, allow padding to be copied. This often
  1382. /// yields more efficient.
  1383. void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr,
  1384. QualType EltTy, bool isVolatile=false,
  1385. CharUnits Alignment = CharUnits::Zero(),
  1386. bool isAssignment = false);
  1387. /// StartBlock - Start new block named N. If insert block is a dummy block
  1388. /// then reuse it.
  1389. void StartBlock(const char *N);
  1390. /// GetAddrOfLocalVar - Return the address of a local variable.
  1391. llvm::Value *GetAddrOfLocalVar(const VarDecl *VD) {
  1392. llvm::Value *Res = LocalDeclMap[VD];
  1393. assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
  1394. return Res;
  1395. }
  1396. /// getOpaqueLValueMapping - Given an opaque value expression (which
  1397. /// must be mapped to an l-value), return its mapping.
  1398. const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) {
  1399. assert(OpaqueValueMapping::shouldBindAsLValue(e));
  1400. llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
  1401. it = OpaqueLValues.find(e);
  1402. assert(it != OpaqueLValues.end() && "no mapping for opaque value!");
  1403. return it->second;
  1404. }
  1405. /// getOpaqueRValueMapping - Given an opaque value expression (which
  1406. /// must be mapped to an r-value), return its mapping.
  1407. const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) {
  1408. assert(!OpaqueValueMapping::shouldBindAsLValue(e));
  1409. llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
  1410. it = OpaqueRValues.find(e);
  1411. assert(it != OpaqueRValues.end() && "no mapping for opaque value!");
  1412. return it->second;
  1413. }
  1414. /// getAccessedFieldNo - Given an encoded value and a result number, return
  1415. /// the input field number being accessed.
  1416. static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
  1417. llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
  1418. llvm::BasicBlock *GetIndirectGotoBlock();
  1419. /// EmitNullInitialization - Generate code to set a value of the given type to
  1420. /// null, If the type contains data member pointers, they will be initialized
  1421. /// to -1 in accordance with the Itanium C++ ABI.
  1422. void EmitNullInitialization(llvm::Value *DestPtr, QualType Ty);
  1423. // EmitVAArg - Generate code to get an argument from the passed in pointer
  1424. // and update it accordingly. The return value is a pointer to the argument.
  1425. // FIXME: We should be able to get rid of this method and use the va_arg
  1426. // instruction in LLVM instead once it works well enough.
  1427. llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty);
  1428. /// emitArrayLength - Compute the length of an array, even if it's a
  1429. /// VLA, and drill down to the base element type.
  1430. llvm::Value *emitArrayLength(const ArrayType *arrayType,
  1431. QualType &baseType,
  1432. llvm::Value *&addr);
  1433. /// EmitVLASize - Capture all the sizes for the VLA expressions in
  1434. /// the given variably-modified type and store them in the VLASizeMap.
  1435. ///
  1436. /// This function can be called with a null (unreachable) insert point.
  1437. void EmitVariablyModifiedType(QualType Ty);
  1438. /// getVLASize - Returns an LLVM value that corresponds to the size,
  1439. /// in non-variably-sized elements, of a variable length array type,
  1440. /// plus that largest non-variably-sized element type. Assumes that
  1441. /// the type has already been emitted with EmitVariablyModifiedType.
  1442. std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla);
  1443. std::pair<llvm::Value*,QualType> getVLASize(QualType vla);
  1444. /// LoadCXXThis - Load the value of 'this'. This function is only valid while
  1445. /// generating code for an C++ member function.
  1446. llvm::Value *LoadCXXThis() {
  1447. assert(CXXThisValue && "no 'this' value for this function");
  1448. return CXXThisValue;
  1449. }
  1450. /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
  1451. /// virtual bases.
  1452. llvm::Value *LoadCXXVTT() {
  1453. assert(CXXVTTValue && "no VTT value for this function");
  1454. return CXXVTTValue;
  1455. }
  1456. /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
  1457. /// complete class to the given direct base.
  1458. llvm::Value *
  1459. GetAddressOfDirectBaseInCompleteClass(llvm::Value *Value,
  1460. const CXXRecordDecl *Derived,
  1461. const CXXRecordDecl *Base,
  1462. bool BaseIsVirtual);
  1463. /// GetAddressOfBaseClass - This function will add the necessary delta to the
  1464. /// load of 'this' and returns address of the base class.
  1465. llvm::Value *GetAddressOfBaseClass(llvm::Value *Value,
  1466. const CXXRecordDecl *Derived,
  1467. CastExpr::path_const_iterator PathBegin,
  1468. CastExpr::path_const_iterator PathEnd,
  1469. bool NullCheckValue);
  1470. llvm::Value *GetAddressOfDerivedClass(llvm::Value *Value,
  1471. const CXXRecordDecl *Derived,
  1472. CastExpr::path_const_iterator PathBegin,
  1473. CastExpr::path_const_iterator PathEnd,
  1474. bool NullCheckValue);
  1475. llvm::Value *GetVirtualBaseClassOffset(llvm::Value *This,
  1476. const CXXRecordDecl *ClassDecl,
  1477. const CXXRecordDecl *BaseClassDecl);
  1478. void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1479. CXXCtorType CtorType,
  1480. const FunctionArgList &Args);
  1481. // It's important not to confuse this and the previous function. Delegating
  1482. // constructors are the C++0x feature. The constructor delegate optimization
  1483. // is used to reduce duplication in the base and complete consturctors where
  1484. // they are substantially the same.
  1485. void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1486. const FunctionArgList &Args);
  1487. void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
  1488. bool ForVirtualBase, llvm::Value *This,
  1489. CallExpr::const_arg_iterator ArgBeg,
  1490. CallExpr::const_arg_iterator ArgEnd);
  1491. void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
  1492. llvm::Value *This, llvm::Value *Src,
  1493. CallExpr::const_arg_iterator ArgBeg,
  1494. CallExpr::const_arg_iterator ArgEnd);
  1495. void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
  1496. const ConstantArrayType *ArrayTy,
  1497. llvm::Value *ArrayPtr,
  1498. CallExpr::const_arg_iterator ArgBeg,
  1499. CallExpr::const_arg_iterator ArgEnd,
  1500. bool ZeroInitialization = false);
  1501. void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
  1502. llvm::Value *NumElements,
  1503. llvm::Value *ArrayPtr,
  1504. CallExpr::const_arg_iterator ArgBeg,
  1505. CallExpr::const_arg_iterator ArgEnd,
  1506. bool ZeroInitialization = false);
  1507. static Destroyer destroyCXXObject;
  1508. void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
  1509. bool ForVirtualBase, llvm::Value *This);
  1510. void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
  1511. llvm::Value *NewPtr, llvm::Value *NumElements);
  1512. void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
  1513. llvm::Value *Ptr);
  1514. llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
  1515. void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
  1516. void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
  1517. QualType DeleteTy);
  1518. llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E);
  1519. llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *DCE);
  1520. llvm::Value* EmitCXXUuidofExpr(const CXXUuidofExpr *E);
  1521. void MaybeEmitStdInitializerListCleanup(llvm::Value *loc, const Expr *init);
  1522. void EmitStdInitializerListCleanup(llvm::Value *loc,
  1523. const InitListExpr *init);
  1524. /// \brief Situations in which we might emit a check for the suitability of a
  1525. /// pointer or glvalue.
  1526. enum TypeCheckKind {
  1527. /// Checking the operand of a load. Must be suitably sized and aligned.
  1528. TCK_Load,
  1529. /// Checking the destination of a store. Must be suitably sized and aligned.
  1530. TCK_Store,
  1531. /// Checking the bound value in a reference binding. Must be suitably sized
  1532. /// and aligned, but is not required to refer to an object (until the
  1533. /// reference is used), per core issue 453.
  1534. TCK_ReferenceBinding,
  1535. /// Checking the object expression in a non-static data member access. Must
  1536. /// be an object within its lifetime.
  1537. TCK_MemberAccess,
  1538. /// Checking the 'this' pointer for a call to a non-static member function.
  1539. /// Must be an object within its lifetime.
  1540. TCK_MemberCall,
  1541. /// Checking the 'this' pointer for a constructor call.
  1542. TCK_ConstructorCall
  1543. };
  1544. /// \brief Emit a check that \p V is the address of storage of the
  1545. /// appropriate size and alignment for an object of type \p Type.
  1546. void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V,
  1547. QualType Type, CharUnits Alignment = CharUnits::Zero());
  1548. llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
  1549. bool isInc, bool isPre);
  1550. ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
  1551. bool isInc, bool isPre);
  1552. //===--------------------------------------------------------------------===//
  1553. // Declaration Emission
  1554. //===--------------------------------------------------------------------===//
  1555. /// EmitDecl - Emit a declaration.
  1556. ///
  1557. /// This function can be called with a null (unreachable) insert point.
  1558. void EmitDecl(const Decl &D);
  1559. /// EmitVarDecl - Emit a local variable declaration.
  1560. ///
  1561. /// This function can be called with a null (unreachable) insert point.
  1562. void EmitVarDecl(const VarDecl &D);
  1563. void EmitScalarInit(const Expr *init, const ValueDecl *D,
  1564. LValue lvalue, bool capturedByInit);
  1565. void EmitScalarInit(llvm::Value *init, LValue lvalue);
  1566. typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
  1567. llvm::Value *Address);
  1568. /// EmitAutoVarDecl - Emit an auto variable declaration.
  1569. ///
  1570. /// This function can be called with a null (unreachable) insert point.
  1571. void EmitAutoVarDecl(const VarDecl &D);
  1572. class AutoVarEmission {
  1573. friend class CodeGenFunction;
  1574. const VarDecl *Variable;
  1575. /// The alignment of the variable.
  1576. CharUnits Alignment;
  1577. /// The address of the alloca. Null if the variable was emitted
  1578. /// as a global constant.
  1579. llvm::Value *Address;
  1580. llvm::Value *NRVOFlag;
  1581. /// True if the variable is a __block variable.
  1582. bool IsByRef;
  1583. /// True if the variable is of aggregate type and has a constant
  1584. /// initializer.
  1585. bool IsConstantAggregate;
  1586. struct Invalid {};
  1587. AutoVarEmission(Invalid) : Variable(0) {}
  1588. AutoVarEmission(const VarDecl &variable)
  1589. : Variable(&variable), Address(0), NRVOFlag(0),
  1590. IsByRef(false), IsConstantAggregate(false) {}
  1591. bool wasEmittedAsGlobal() const { return Address == 0; }
  1592. public:
  1593. static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
  1594. /// Returns the address of the object within this declaration.
  1595. /// Note that this does not chase the forwarding pointer for
  1596. /// __block decls.
  1597. llvm::Value *getObjectAddress(CodeGenFunction &CGF) const {
  1598. if (!IsByRef) return Address;
  1599. return CGF.Builder.CreateStructGEP(Address,
  1600. CGF.getByRefValueLLVMField(Variable),
  1601. Variable->getNameAsString());
  1602. }
  1603. };
  1604. AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
  1605. void EmitAutoVarInit(const AutoVarEmission &emission);
  1606. void EmitAutoVarCleanups(const AutoVarEmission &emission);
  1607. void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
  1608. QualType::DestructionKind dtorKind);
  1609. void EmitStaticVarDecl(const VarDecl &D,
  1610. llvm::GlobalValue::LinkageTypes Linkage);
  1611. /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
  1612. void EmitParmDecl(const VarDecl &D, llvm::Value *Arg, unsigned ArgNo);
  1613. /// protectFromPeepholes - Protect a value that we're intending to
  1614. /// store to the side, but which will probably be used later, from
  1615. /// aggressive peepholing optimizations that might delete it.
  1616. ///
  1617. /// Pass the result to unprotectFromPeepholes to declare that
  1618. /// protection is no longer required.
  1619. ///
  1620. /// There's no particular reason why this shouldn't apply to
  1621. /// l-values, it's just that no existing peepholes work on pointers.
  1622. PeepholeProtection protectFromPeepholes(RValue rvalue);
  1623. void unprotectFromPeepholes(PeepholeProtection protection);
  1624. //===--------------------------------------------------------------------===//
  1625. // Statement Emission
  1626. //===--------------------------------------------------------------------===//
  1627. /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
  1628. void EmitStopPoint(const Stmt *S);
  1629. /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
  1630. /// this function even if there is no current insertion point.
  1631. ///
  1632. /// This function may clear the current insertion point; callers should use
  1633. /// EnsureInsertPoint if they wish to subsequently generate code without first
  1634. /// calling EmitBlock, EmitBranch, or EmitStmt.
  1635. void EmitStmt(const Stmt *S);
  1636. /// EmitSimpleStmt - Try to emit a "simple" statement which does not
  1637. /// necessarily require an insertion point or debug information; typically
  1638. /// because the statement amounts to a jump or a container of other
  1639. /// statements.
  1640. ///
  1641. /// \return True if the statement was handled.
  1642. bool EmitSimpleStmt(const Stmt *S);
  1643. RValue EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
  1644. AggValueSlot AVS = AggValueSlot::ignored());
  1645. /// EmitLabel - Emit the block for the given label. It is legal to call this
  1646. /// function even if there is no current insertion point.
  1647. void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
  1648. void EmitLabelStmt(const LabelStmt &S);
  1649. void EmitAttributedStmt(const AttributedStmt &S);
  1650. void EmitGotoStmt(const GotoStmt &S);
  1651. void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
  1652. void EmitIfStmt(const IfStmt &S);
  1653. void EmitWhileStmt(const WhileStmt &S);
  1654. void EmitDoStmt(const DoStmt &S);
  1655. void EmitForStmt(const ForStmt &S);
  1656. void EmitReturnStmt(const ReturnStmt &S);
  1657. void EmitDeclStmt(const DeclStmt &S);
  1658. void EmitBreakStmt(const BreakStmt &S);
  1659. void EmitContinueStmt(const ContinueStmt &S);
  1660. void EmitSwitchStmt(const SwitchStmt &S);
  1661. void EmitDefaultStmt(const DefaultStmt &S);
  1662. void EmitCaseStmt(const CaseStmt &S);
  1663. void EmitCaseStmtRange(const CaseStmt &S);
  1664. void EmitAsmStmt(const AsmStmt &S);
  1665. void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
  1666. void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
  1667. void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
  1668. void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
  1669. void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S);
  1670. llvm::Constant *getUnwindResumeFn();
  1671. llvm::Constant *getUnwindResumeOrRethrowFn();
  1672. void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
  1673. void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
  1674. void EmitCXXTryStmt(const CXXTryStmt &S);
  1675. void EmitCXXForRangeStmt(const CXXForRangeStmt &S);
  1676. //===--------------------------------------------------------------------===//
  1677. // LValue Expression Emission
  1678. //===--------------------------------------------------------------------===//
  1679. /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
  1680. RValue GetUndefRValue(QualType Ty);
  1681. /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
  1682. /// and issue an ErrorUnsupported style diagnostic (using the
  1683. /// provided Name).
  1684. RValue EmitUnsupportedRValue(const Expr *E,
  1685. const char *Name);
  1686. /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
  1687. /// an ErrorUnsupported style diagnostic (using the provided Name).
  1688. LValue EmitUnsupportedLValue(const Expr *E,
  1689. const char *Name);
  1690. /// EmitLValue - Emit code to compute a designator that specifies the location
  1691. /// of the expression.
  1692. ///
  1693. /// This can return one of two things: a simple address or a bitfield
  1694. /// reference. In either case, the LLVM Value* in the LValue structure is
  1695. /// guaranteed to be an LLVM pointer type.
  1696. ///
  1697. /// If this returns a bitfield reference, nothing about the pointee type of
  1698. /// the LLVM value is known: For example, it may not be a pointer to an
  1699. /// integer.
  1700. ///
  1701. /// If this returns a normal address, and if the lvalue's C type is fixed
  1702. /// size, this method guarantees that the returned pointer type will point to
  1703. /// an LLVM type of the same size of the lvalue's type. If the lvalue has a
  1704. /// variable length type, this is not possible.
  1705. ///
  1706. LValue EmitLValue(const Expr *E);
  1707. /// \brief Same as EmitLValue but additionally we generate checking code to
  1708. /// guard against undefined behavior. This is only suitable when we know
  1709. /// that the address will be used to access the object.
  1710. LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK);
  1711. /// EmitToMemory - Change a scalar value from its value
  1712. /// representation to its in-memory representation.
  1713. llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
  1714. /// EmitFromMemory - Change a scalar value from its memory
  1715. /// representation to its value representation.
  1716. llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
  1717. /// EmitLoadOfScalar - Load a scalar value from an address, taking
  1718. /// care to appropriately convert from the memory representation to
  1719. /// the LLVM value representation.
  1720. llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
  1721. unsigned Alignment, QualType Ty,
  1722. llvm::MDNode *TBAAInfo = 0);
  1723. /// EmitLoadOfScalar - Load a scalar value from an address, taking
  1724. /// care to appropriately convert from the memory representation to
  1725. /// the LLVM value representation. The l-value must be a simple
  1726. /// l-value.
  1727. llvm::Value *EmitLoadOfScalar(LValue lvalue);
  1728. /// EmitStoreOfScalar - Store a scalar value to an address, taking
  1729. /// care to appropriately convert from the memory representation to
  1730. /// the LLVM value representation.
  1731. void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
  1732. bool Volatile, unsigned Alignment, QualType Ty,
  1733. llvm::MDNode *TBAAInfo = 0, bool isInit=false);
  1734. /// EmitStoreOfScalar - Store a scalar value to an address, taking
  1735. /// care to appropriately convert from the memory representation to
  1736. /// the LLVM value representation. The l-value must be a simple
  1737. /// l-value. The isInit flag indicates whether this is an initialization.
  1738. /// If so, atomic qualifiers are ignored and the store is always non-atomic.
  1739. void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false);
  1740. /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
  1741. /// this method emits the address of the lvalue, then loads the result as an
  1742. /// rvalue, returning the rvalue.
  1743. RValue EmitLoadOfLValue(LValue V);
  1744. RValue EmitLoadOfExtVectorElementLValue(LValue V);
  1745. RValue EmitLoadOfBitfieldLValue(LValue LV);
  1746. /// EmitStoreThroughLValue - Store the specified rvalue into the specified
  1747. /// lvalue, where both are guaranteed to the have the same type, and that type
  1748. /// is 'Ty'.
  1749. void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false);
  1750. void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
  1751. /// EmitStoreThroughLValue - Store Src into Dst with same constraints as
  1752. /// EmitStoreThroughLValue.
  1753. ///
  1754. /// \param Result [out] - If non-null, this will be set to a Value* for the
  1755. /// bit-field contents after the store, appropriate for use as the result of
  1756. /// an assignment to the bit-field.
  1757. void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
  1758. llvm::Value **Result=0);
  1759. /// Emit an l-value for an assignment (simple or compound) of complex type.
  1760. LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
  1761. LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
  1762. // Note: only available for agg return types
  1763. LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
  1764. LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
  1765. // Note: only available for agg return types
  1766. LValue EmitCallExprLValue(const CallExpr *E);
  1767. // Note: only available for agg return types
  1768. LValue EmitVAArgExprLValue(const VAArgExpr *E);
  1769. LValue EmitDeclRefLValue(const DeclRefExpr *E);
  1770. LValue EmitStringLiteralLValue(const StringLiteral *E);
  1771. LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
  1772. LValue EmitPredefinedLValue(const PredefinedExpr *E);
  1773. LValue EmitUnaryOpLValue(const UnaryOperator *E);
  1774. LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E);
  1775. LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
  1776. LValue EmitMemberExpr(const MemberExpr *E);
  1777. LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
  1778. LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
  1779. LValue EmitInitListLValue(const InitListExpr *E);
  1780. LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E);
  1781. LValue EmitCastLValue(const CastExpr *E);
  1782. LValue EmitNullInitializationLValue(const CXXScalarValueInitExpr *E);
  1783. LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  1784. LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
  1785. RValue EmitRValueForField(LValue LV, const FieldDecl *FD);
  1786. class ConstantEmission {
  1787. llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference;
  1788. ConstantEmission(llvm::Constant *C, bool isReference)
  1789. : ValueAndIsReference(C, isReference) {}
  1790. public:
  1791. ConstantEmission() {}
  1792. static ConstantEmission forReference(llvm::Constant *C) {
  1793. return ConstantEmission(C, true);
  1794. }
  1795. static ConstantEmission forValue(llvm::Constant *C) {
  1796. return ConstantEmission(C, false);
  1797. }
  1798. operator bool() const { return ValueAndIsReference.getOpaqueValue() != 0; }
  1799. bool isReference() const { return ValueAndIsReference.getInt(); }
  1800. LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const {
  1801. assert(isReference());
  1802. return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(),
  1803. refExpr->getType());
  1804. }
  1805. llvm::Constant *getValue() const {
  1806. assert(!isReference());
  1807. return ValueAndIsReference.getPointer();
  1808. }
  1809. };
  1810. ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr);
  1811. RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e,
  1812. AggValueSlot slot = AggValueSlot::ignored());
  1813. LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e);
  1814. llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
  1815. const ObjCIvarDecl *Ivar);
  1816. LValue EmitLValueForField(LValue Base, const FieldDecl* Field);
  1817. /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
  1818. /// if the Field is a reference, this will return the address of the reference
  1819. /// and not the address of the value stored in the reference.
  1820. LValue EmitLValueForFieldInitialization(LValue Base,
  1821. const FieldDecl* Field);
  1822. LValue EmitLValueForIvar(QualType ObjectTy,
  1823. llvm::Value* Base, const ObjCIvarDecl *Ivar,
  1824. unsigned CVRQualifiers);
  1825. LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
  1826. LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
  1827. LValue EmitLambdaLValue(const LambdaExpr *E);
  1828. LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
  1829. LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E);
  1830. LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
  1831. LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
  1832. LValue EmitStmtExprLValue(const StmtExpr *E);
  1833. LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
  1834. LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
  1835. void EmitDeclRefExprDbgValue(const DeclRefExpr *E, llvm::Constant *Init);
  1836. //===--------------------------------------------------------------------===//
  1837. // Scalar Expression Emission
  1838. //===--------------------------------------------------------------------===//
  1839. /// EmitCall - Generate a call of the given function, expecting the given
  1840. /// result type, and using the given argument list which specifies both the
  1841. /// LLVM arguments and the types they were derived from.
  1842. ///
  1843. /// \param TargetDecl - If given, the decl of the function in a direct call;
  1844. /// used to set attributes on the call (noreturn, etc.).
  1845. RValue EmitCall(const CGFunctionInfo &FnInfo,
  1846. llvm::Value *Callee,
  1847. ReturnValueSlot ReturnValue,
  1848. const CallArgList &Args,
  1849. const Decl *TargetDecl = 0,
  1850. llvm::Instruction **callOrInvoke = 0);
  1851. RValue EmitCall(QualType FnType, llvm::Value *Callee,
  1852. ReturnValueSlot ReturnValue,
  1853. CallExpr::const_arg_iterator ArgBeg,
  1854. CallExpr::const_arg_iterator ArgEnd,
  1855. const Decl *TargetDecl = 0);
  1856. RValue EmitCallExpr(const CallExpr *E,
  1857. ReturnValueSlot ReturnValue = ReturnValueSlot());
  1858. llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
  1859. ArrayRef<llvm::Value *> Args,
  1860. const Twine &Name = "");
  1861. llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
  1862. const Twine &Name = "");
  1863. llvm::Value *BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
  1864. llvm::Type *Ty);
  1865. llvm::Value *BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
  1866. llvm::Value *This, llvm::Type *Ty);
  1867. llvm::Value *BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
  1868. NestedNameSpecifier *Qual,
  1869. llvm::Type *Ty);
  1870. llvm::Value *BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD,
  1871. CXXDtorType Type,
  1872. const CXXRecordDecl *RD);
  1873. RValue EmitCXXMemberCall(const CXXMethodDecl *MD,
  1874. SourceLocation CallLoc,
  1875. llvm::Value *Callee,
  1876. ReturnValueSlot ReturnValue,
  1877. llvm::Value *This,
  1878. llvm::Value *VTT,
  1879. CallExpr::const_arg_iterator ArgBeg,
  1880. CallExpr::const_arg_iterator ArgEnd);
  1881. RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
  1882. ReturnValueSlot ReturnValue);
  1883. RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
  1884. ReturnValueSlot ReturnValue);
  1885. llvm::Value *EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
  1886. const CXXMethodDecl *MD,
  1887. llvm::Value *This);
  1888. RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
  1889. const CXXMethodDecl *MD,
  1890. ReturnValueSlot ReturnValue);
  1891. RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
  1892. ReturnValueSlot ReturnValue);
  1893. RValue EmitBuiltinExpr(const FunctionDecl *FD,
  1894. unsigned BuiltinID, const CallExpr *E);
  1895. RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
  1896. /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
  1897. /// is unhandled by the current target.
  1898. llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  1899. llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  1900. llvm::Value *EmitNeonCall(llvm::Function *F,
  1901. SmallVectorImpl<llvm::Value*> &O,
  1902. const char *name,
  1903. unsigned shift = 0, bool rightshift = false);
  1904. llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
  1905. llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty,
  1906. bool negateForRightShift);
  1907. llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops);
  1908. llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  1909. llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  1910. llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
  1911. llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
  1912. llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E);
  1913. llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E);
  1914. llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E);
  1915. llvm::Value *EmitObjCCollectionLiteral(const Expr *E,
  1916. const ObjCMethodDecl *MethodWithObjects);
  1917. llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
  1918. RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
  1919. ReturnValueSlot Return = ReturnValueSlot());
  1920. /// Retrieves the default cleanup kind for an ARC cleanup.
  1921. /// Except under -fobjc-arc-eh, ARC cleanups are normal-only.
  1922. CleanupKind getARCCleanupKind() {
  1923. return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions
  1924. ? NormalAndEHCleanup : NormalCleanup;
  1925. }
  1926. // ARC primitives.
  1927. void EmitARCInitWeak(llvm::Value *value, llvm::Value *addr);
  1928. void EmitARCDestroyWeak(llvm::Value *addr);
  1929. llvm::Value *EmitARCLoadWeak(llvm::Value *addr);
  1930. llvm::Value *EmitARCLoadWeakRetained(llvm::Value *addr);
  1931. llvm::Value *EmitARCStoreWeak(llvm::Value *value, llvm::Value *addr,
  1932. bool ignored);
  1933. void EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src);
  1934. void EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src);
  1935. llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value);
  1936. llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value);
  1937. llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value,
  1938. bool ignored);
  1939. llvm::Value *EmitARCStoreStrongCall(llvm::Value *addr, llvm::Value *value,
  1940. bool ignored);
  1941. llvm::Value *EmitARCRetain(QualType type, llvm::Value *value);
  1942. llvm::Value *EmitARCRetainNonBlock(llvm::Value *value);
  1943. llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory);
  1944. void EmitARCDestroyStrong(llvm::Value *addr, bool precise);
  1945. void EmitARCRelease(llvm::Value *value, bool precise);
  1946. llvm::Value *EmitARCAutorelease(llvm::Value *value);
  1947. llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value);
  1948. llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value);
  1949. llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value);
  1950. std::pair<LValue,llvm::Value*>
  1951. EmitARCStoreAutoreleasing(const BinaryOperator *e);
  1952. std::pair<LValue,llvm::Value*>
  1953. EmitARCStoreStrong(const BinaryOperator *e, bool ignored);
  1954. llvm::Value *EmitObjCThrowOperand(const Expr *expr);
  1955. llvm::Value *EmitObjCProduceObject(QualType T, llvm::Value *Ptr);
  1956. llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr);
  1957. llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr);
  1958. llvm::Value *EmitARCExtendBlockObject(const Expr *expr);
  1959. llvm::Value *EmitARCRetainScalarExpr(const Expr *expr);
  1960. llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr);
  1961. static Destroyer destroyARCStrongImprecise;
  1962. static Destroyer destroyARCStrongPrecise;
  1963. static Destroyer destroyARCWeak;
  1964. void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr);
  1965. llvm::Value *EmitObjCAutoreleasePoolPush();
  1966. llvm::Value *EmitObjCMRRAutoreleasePoolPush();
  1967. void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr);
  1968. void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr);
  1969. /// EmitReferenceBindingToExpr - Emits a reference binding to the passed in
  1970. /// expression. Will emit a temporary variable if E is not an LValue.
  1971. RValue EmitReferenceBindingToExpr(const Expr* E,
  1972. const NamedDecl *InitializedDecl);
  1973. //===--------------------------------------------------------------------===//
  1974. // Expression Emission
  1975. //===--------------------------------------------------------------------===//
  1976. // Expressions are broken into three classes: scalar, complex, aggregate.
  1977. /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
  1978. /// scalar type, returning the result.
  1979. llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
  1980. /// EmitScalarConversion - Emit a conversion from the specified type to the
  1981. /// specified destination type, both of which are LLVM scalar types.
  1982. llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
  1983. QualType DstTy);
  1984. /// EmitComplexToScalarConversion - Emit a conversion from the specified
  1985. /// complex type to the specified destination type, where the destination type
  1986. /// is an LLVM scalar type.
  1987. llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
  1988. QualType DstTy);
  1989. /// EmitAggExpr - Emit the computation of the specified expression
  1990. /// of aggregate type. The result is computed into the given slot,
  1991. /// which may be null to indicate that the value is not needed.
  1992. void EmitAggExpr(const Expr *E, AggValueSlot AS);
  1993. /// EmitAggExprToLValue - Emit the computation of the specified expression of
  1994. /// aggregate type into a temporary LValue.
  1995. LValue EmitAggExprToLValue(const Expr *E);
  1996. /// EmitGCMemmoveCollectable - Emit special API for structs with object
  1997. /// pointers.
  1998. void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr,
  1999. QualType Ty);
  2000. /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
  2001. /// make sure it survives garbage collection until this point.
  2002. void EmitExtendGCLifetime(llvm::Value *object);
  2003. /// EmitComplexExpr - Emit the computation of the specified expression of
  2004. /// complex type, returning the result.
  2005. ComplexPairTy EmitComplexExpr(const Expr *E,
  2006. bool IgnoreReal = false,
  2007. bool IgnoreImag = false);
  2008. /// EmitComplexExprIntoAddr - Emit the computation of the specified expression
  2009. /// of complex type, storing into the specified Value*.
  2010. void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr,
  2011. bool DestIsVolatile);
  2012. /// StoreComplexToAddr - Store a complex number into the specified address.
  2013. void StoreComplexToAddr(ComplexPairTy V, llvm::Value *DestAddr,
  2014. bool DestIsVolatile);
  2015. /// LoadComplexFromAddr - Load a complex number from the specified address.
  2016. ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile);
  2017. /// CreateStaticVarDecl - Create a zero-initialized LLVM global for
  2018. /// a static local variable.
  2019. llvm::GlobalVariable *CreateStaticVarDecl(const VarDecl &D,
  2020. const char *Separator,
  2021. llvm::GlobalValue::LinkageTypes Linkage);
  2022. /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
  2023. /// global variable that has already been created for it. If the initializer
  2024. /// has a different type than GV does, this may free GV and return a different
  2025. /// one. Otherwise it just returns GV.
  2026. llvm::GlobalVariable *
  2027. AddInitializerToStaticVarDecl(const VarDecl &D,
  2028. llvm::GlobalVariable *GV);
  2029. /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
  2030. /// variable with global storage.
  2031. void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr,
  2032. bool PerformInit);
  2033. /// Call atexit() with a function that passes the given argument to
  2034. /// the given function.
  2035. void registerGlobalDtorWithAtExit(llvm::Constant *fn, llvm::Constant *addr);
  2036. /// Emit code in this function to perform a guarded variable
  2037. /// initialization. Guarded initializations are used when it's not
  2038. /// possible to prove that an initialization will be done exactly
  2039. /// once, e.g. with a static local variable or a static data member
  2040. /// of a class template.
  2041. void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr,
  2042. bool PerformInit);
  2043. /// GenerateCXXGlobalInitFunc - Generates code for initializing global
  2044. /// variables.
  2045. void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
  2046. llvm::Constant **Decls,
  2047. unsigned NumDecls);
  2048. /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global
  2049. /// variables.
  2050. void GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
  2051. const std::vector<std::pair<llvm::WeakVH,
  2052. llvm::Constant*> > &DtorsAndObjects);
  2053. void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
  2054. const VarDecl *D,
  2055. llvm::GlobalVariable *Addr,
  2056. bool PerformInit);
  2057. void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
  2058. void EmitSynthesizedCXXCopyCtor(llvm::Value *Dest, llvm::Value *Src,
  2059. const Expr *Exp);
  2060. void enterFullExpression(const ExprWithCleanups *E) {
  2061. if (E->getNumObjects() == 0) return;
  2062. enterNonTrivialFullExpression(E);
  2063. }
  2064. void enterNonTrivialFullExpression(const ExprWithCleanups *E);
  2065. void EmitCXXThrowExpr(const CXXThrowExpr *E);
  2066. void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest);
  2067. RValue EmitAtomicExpr(AtomicExpr *E, llvm::Value *Dest = 0);
  2068. //===--------------------------------------------------------------------===//
  2069. // Annotations Emission
  2070. //===--------------------------------------------------------------------===//
  2071. /// Emit an annotation call (intrinsic or builtin).
  2072. llvm::Value *EmitAnnotationCall(llvm::Value *AnnotationFn,
  2073. llvm::Value *AnnotatedVal,
  2074. StringRef AnnotationStr,
  2075. SourceLocation Location);
  2076. /// Emit local annotations for the local variable V, declared by D.
  2077. void EmitVarAnnotations(const VarDecl *D, llvm::Value *V);
  2078. /// Emit field annotations for the given field & value. Returns the
  2079. /// annotation result.
  2080. llvm::Value *EmitFieldAnnotations(const FieldDecl *D, llvm::Value *V);
  2081. //===--------------------------------------------------------------------===//
  2082. // Internal Helpers
  2083. //===--------------------------------------------------------------------===//
  2084. /// ContainsLabel - Return true if the statement contains a label in it. If
  2085. /// this statement is not executed normally, it not containing a label means
  2086. /// that we can just remove the code.
  2087. static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
  2088. /// containsBreak - Return true if the statement contains a break out of it.
  2089. /// If the statement (recursively) contains a switch or loop with a break
  2090. /// inside of it, this is fine.
  2091. static bool containsBreak(const Stmt *S);
  2092. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  2093. /// to a constant, or if it does but contains a label, return false. If it
  2094. /// constant folds return true and set the boolean result in Result.
  2095. bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result);
  2096. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  2097. /// to a constant, or if it does but contains a label, return false. If it
  2098. /// constant folds return true and set the folded value.
  2099. bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result);
  2100. /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
  2101. /// if statement) to the specified blocks. Based on the condition, this might
  2102. /// try to simplify the codegen of the conditional based on the branch.
  2103. void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
  2104. llvm::BasicBlock *FalseBlock);
  2105. /// \brief Emit a description of a type in a format suitable for passing to
  2106. /// a runtime sanitizer handler.
  2107. llvm::Constant *EmitCheckTypeDescriptor(QualType T);
  2108. /// \brief Convert a value into a format suitable for passing to a runtime
  2109. /// sanitizer handler.
  2110. llvm::Value *EmitCheckValue(llvm::Value *V);
  2111. /// \brief Emit a description of a source location in a format suitable for
  2112. /// passing to a runtime sanitizer handler.
  2113. llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc);
  2114. /// \brief Specify under what conditions this check can be recovered
  2115. enum CheckRecoverableKind {
  2116. /// Always terminate program execution if this check fails
  2117. CRK_Unrecoverable,
  2118. /// Check supports recovering, allows user to specify which
  2119. CRK_Recoverable,
  2120. /// Runtime conditionally aborts, always need to support recovery.
  2121. CRK_AlwaysRecoverable
  2122. };
  2123. /// \brief Create a basic block that will call a handler function in a
  2124. /// sanitizer runtime with the provided arguments, and create a conditional
  2125. /// branch to it.
  2126. void EmitCheck(llvm::Value *Checked, StringRef CheckName,
  2127. ArrayRef<llvm::Constant *> StaticArgs,
  2128. ArrayRef<llvm::Value *> DynamicArgs,
  2129. CheckRecoverableKind Recoverable);
  2130. /// \brief Create a basic block that will call the trap intrinsic, and emit a
  2131. /// conditional branch to it, for the -ftrapv checks.
  2132. void EmitTrapvCheck(llvm::Value *Checked);
  2133. /// EmitCallArg - Emit a single call argument.
  2134. void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType);
  2135. /// EmitDelegateCallArg - We are performing a delegate call; that
  2136. /// is, the current function is delegating to another one. Produce
  2137. /// a r-value suitable for passing the given parameter.
  2138. void EmitDelegateCallArg(CallArgList &args, const VarDecl *param);
  2139. /// SetFPAccuracy - Set the minimum required accuracy of the given floating
  2140. /// point operation, expressed as the maximum relative error in ulp.
  2141. void SetFPAccuracy(llvm::Value *Val, float Accuracy);
  2142. private:
  2143. llvm::MDNode *getRangeForLoadFromType(QualType Ty);
  2144. void EmitReturnOfRValue(RValue RV, QualType Ty);
  2145. /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
  2146. /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
  2147. ///
  2148. /// \param AI - The first function argument of the expansion.
  2149. /// \return The argument following the last expanded function
  2150. /// argument.
  2151. llvm::Function::arg_iterator
  2152. ExpandTypeFromArgs(QualType Ty, LValue Dst,
  2153. llvm::Function::arg_iterator AI);
  2154. /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg
  2155. /// Ty, into individual arguments on the provided vector \arg Args. See
  2156. /// ABIArgInfo::Expand.
  2157. void ExpandTypeToArgs(QualType Ty, RValue Src,
  2158. SmallVector<llvm::Value*, 16> &Args,
  2159. llvm::FunctionType *IRFuncTy);
  2160. llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info,
  2161. const Expr *InputExpr, std::string &ConstraintStr);
  2162. llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
  2163. LValue InputValue, QualType InputType,
  2164. std::string &ConstraintStr);
  2165. /// EmitCallArgs - Emit call arguments for a function.
  2166. /// The CallArgTypeInfo parameter is used for iterating over the known
  2167. /// argument types of the function being called.
  2168. template<typename T>
  2169. void EmitCallArgs(CallArgList& Args, const T* CallArgTypeInfo,
  2170. CallExpr::const_arg_iterator ArgBeg,
  2171. CallExpr::const_arg_iterator ArgEnd) {
  2172. CallExpr::const_arg_iterator Arg = ArgBeg;
  2173. // First, use the argument types that the type info knows about
  2174. if (CallArgTypeInfo) {
  2175. for (typename T::arg_type_iterator I = CallArgTypeInfo->arg_type_begin(),
  2176. E = CallArgTypeInfo->arg_type_end(); I != E; ++I, ++Arg) {
  2177. assert(Arg != ArgEnd && "Running over edge of argument list!");
  2178. QualType ArgType = *I;
  2179. #ifndef NDEBUG
  2180. QualType ActualArgType = Arg->getType();
  2181. if (ArgType->isPointerType() && ActualArgType->isPointerType()) {
  2182. QualType ActualBaseType =
  2183. ActualArgType->getAs<PointerType>()->getPointeeType();
  2184. QualType ArgBaseType =
  2185. ArgType->getAs<PointerType>()->getPointeeType();
  2186. if (ArgBaseType->isVariableArrayType()) {
  2187. if (const VariableArrayType *VAT =
  2188. getContext().getAsVariableArrayType(ActualBaseType)) {
  2189. if (!VAT->getSizeExpr())
  2190. ActualArgType = ArgType;
  2191. }
  2192. }
  2193. }
  2194. assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
  2195. getTypePtr() ==
  2196. getContext().getCanonicalType(ActualArgType).getTypePtr() &&
  2197. "type mismatch in call argument!");
  2198. #endif
  2199. EmitCallArg(Args, *Arg, ArgType);
  2200. }
  2201. // Either we've emitted all the call args, or we have a call to a
  2202. // variadic function.
  2203. assert((Arg == ArgEnd || CallArgTypeInfo->isVariadic()) &&
  2204. "Extra arguments in non-variadic function!");
  2205. }
  2206. // If we still have any arguments, emit them using the type of the argument.
  2207. for (; Arg != ArgEnd; ++Arg)
  2208. EmitCallArg(Args, *Arg, Arg->getType());
  2209. }
  2210. const TargetCodeGenInfo &getTargetHooks() const {
  2211. return CGM.getTargetCodeGenInfo();
  2212. }
  2213. void EmitDeclMetadata();
  2214. CodeGenModule::ByrefHelpers *
  2215. buildByrefHelpers(llvm::StructType &byrefType,
  2216. const AutoVarEmission &emission);
  2217. void AddObjCARCExceptionMetadata(llvm::Instruction *Inst);
  2218. /// GetPointeeAlignment - Given an expression with a pointer type, emit the
  2219. /// value and compute our best estimate of the alignment of the pointee.
  2220. std::pair<llvm::Value*, unsigned> EmitPointerWithAlignment(const Expr *Addr);
  2221. };
  2222. /// Helper class with most of the code for saving a value for a
  2223. /// conditional expression cleanup.
  2224. struct DominatingLLVMValue {
  2225. typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
  2226. /// Answer whether the given value needs extra work to be saved.
  2227. static bool needsSaving(llvm::Value *value) {
  2228. // If it's not an instruction, we don't need to save.
  2229. if (!isa<llvm::Instruction>(value)) return false;
  2230. // If it's an instruction in the entry block, we don't need to save.
  2231. llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
  2232. return (block != &block->getParent()->getEntryBlock());
  2233. }
  2234. /// Try to save the given value.
  2235. static saved_type save(CodeGenFunction &CGF, llvm::Value *value) {
  2236. if (!needsSaving(value)) return saved_type(value, false);
  2237. // Otherwise we need an alloca.
  2238. llvm::Value *alloca =
  2239. CGF.CreateTempAlloca(value->getType(), "cond-cleanup.save");
  2240. CGF.Builder.CreateStore(value, alloca);
  2241. return saved_type(alloca, true);
  2242. }
  2243. static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) {
  2244. if (!value.getInt()) return value.getPointer();
  2245. return CGF.Builder.CreateLoad(value.getPointer());
  2246. }
  2247. };
  2248. /// A partial specialization of DominatingValue for llvm::Values that
  2249. /// might be llvm::Instructions.
  2250. template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
  2251. typedef T *type;
  2252. static type restore(CodeGenFunction &CGF, saved_type value) {
  2253. return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
  2254. }
  2255. };
  2256. /// A specialization of DominatingValue for RValue.
  2257. template <> struct DominatingValue<RValue> {
  2258. typedef RValue type;
  2259. class saved_type {
  2260. enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
  2261. AggregateAddress, ComplexAddress };
  2262. llvm::Value *Value;
  2263. Kind K;
  2264. saved_type(llvm::Value *v, Kind k) : Value(v), K(k) {}
  2265. public:
  2266. static bool needsSaving(RValue value);
  2267. static saved_type save(CodeGenFunction &CGF, RValue value);
  2268. RValue restore(CodeGenFunction &CGF);
  2269. // implementations in CGExprCXX.cpp
  2270. };
  2271. static bool needsSaving(type value) {
  2272. return saved_type::needsSaving(value);
  2273. }
  2274. static saved_type save(CodeGenFunction &CGF, type value) {
  2275. return saved_type::save(CGF, value);
  2276. }
  2277. static type restore(CodeGenFunction &CGF, saved_type value) {
  2278. return value.restore(CGF);
  2279. }
  2280. };
  2281. } // end namespace CodeGen
  2282. } // end namespace clang
  2283. #endif