CodeGenFunction.h 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261
  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 "clang/AST/Type.h"
  16. #include "clang/AST/ExprCXX.h"
  17. #include "clang/AST/ExprObjC.h"
  18. #include "clang/AST/CharUnits.h"
  19. #include "clang/Basic/ABI.h"
  20. #include "clang/Basic/TargetInfo.h"
  21. #include "llvm/ADT/DenseMap.h"
  22. #include "llvm/ADT/SmallVector.h"
  23. #include "llvm/Support/ValueHandle.h"
  24. #include "CodeGenModule.h"
  25. #include "CGBuilder.h"
  26. #include "CGValue.h"
  27. namespace llvm {
  28. class BasicBlock;
  29. class LLVMContext;
  30. class MDNode;
  31. class Module;
  32. class SwitchInst;
  33. class Twine;
  34. class Value;
  35. class CallSite;
  36. }
  37. namespace clang {
  38. class APValue;
  39. class ASTContext;
  40. class CXXDestructorDecl;
  41. class CXXTryStmt;
  42. class Decl;
  43. class LabelDecl;
  44. class EnumConstantDecl;
  45. class FunctionDecl;
  46. class FunctionProtoType;
  47. class LabelStmt;
  48. class ObjCContainerDecl;
  49. class ObjCInterfaceDecl;
  50. class ObjCIvarDecl;
  51. class ObjCMethodDecl;
  52. class ObjCImplementationDecl;
  53. class ObjCPropertyImplDecl;
  54. class TargetInfo;
  55. class TargetCodeGenInfo;
  56. class VarDecl;
  57. class ObjCForCollectionStmt;
  58. class ObjCAtTryStmt;
  59. class ObjCAtThrowStmt;
  60. class ObjCAtSynchronizedStmt;
  61. namespace CodeGen {
  62. class CodeGenTypes;
  63. class CGDebugInfo;
  64. class CGFunctionInfo;
  65. class CGRecordLayout;
  66. class CGBlockInfo;
  67. class CGCXXABI;
  68. class BlockFlags;
  69. class BlockFieldFlags;
  70. /// A branch fixup. These are required when emitting a goto to a
  71. /// label which hasn't been emitted yet. The goto is optimistically
  72. /// emitted as a branch to the basic block for the label, and (if it
  73. /// occurs in a scope with non-trivial cleanups) a fixup is added to
  74. /// the innermost cleanup. When a (normal) cleanup is popped, any
  75. /// unresolved fixups in that scope are threaded through the cleanup.
  76. struct BranchFixup {
  77. /// The block containing the terminator which needs to be modified
  78. /// into a switch if this fixup is resolved into the current scope.
  79. /// If null, LatestBranch points directly to the destination.
  80. llvm::BasicBlock *OptimisticBranchBlock;
  81. /// The ultimate destination of the branch.
  82. ///
  83. /// This can be set to null to indicate that this fixup was
  84. /// successfully resolved.
  85. llvm::BasicBlock *Destination;
  86. /// The destination index value.
  87. unsigned DestinationIndex;
  88. /// The initial branch of the fixup.
  89. llvm::BranchInst *InitialBranch;
  90. };
  91. template <class T> struct InvariantValue {
  92. typedef T type;
  93. typedef T saved_type;
  94. static bool needsSaving(type value) { return false; }
  95. static saved_type save(CodeGenFunction &CGF, type value) { return value; }
  96. static type restore(CodeGenFunction &CGF, saved_type value) { return value; }
  97. };
  98. /// A metaprogramming class for ensuring that a value will dominate an
  99. /// arbitrary position in a function.
  100. template <class T> struct DominatingValue : InvariantValue<T> {};
  101. template <class T, bool mightBeInstruction =
  102. llvm::is_base_of<llvm::Value, T>::value &&
  103. !llvm::is_base_of<llvm::Constant, T>::value &&
  104. !llvm::is_base_of<llvm::BasicBlock, T>::value>
  105. struct DominatingPointer;
  106. template <class T> struct DominatingPointer<T,false> : InvariantValue<T*> {};
  107. // template <class T> struct DominatingPointer<T,true> at end of file
  108. template <class T> struct DominatingValue<T*> : DominatingPointer<T> {};
  109. enum CleanupKind {
  110. EHCleanup = 0x1,
  111. NormalCleanup = 0x2,
  112. NormalAndEHCleanup = EHCleanup | NormalCleanup,
  113. InactiveCleanup = 0x4,
  114. InactiveEHCleanup = EHCleanup | InactiveCleanup,
  115. InactiveNormalCleanup = NormalCleanup | InactiveCleanup,
  116. InactiveNormalAndEHCleanup = NormalAndEHCleanup | InactiveCleanup
  117. };
  118. /// A stack of scopes which respond to exceptions, including cleanups
  119. /// and catch blocks.
  120. class EHScopeStack {
  121. public:
  122. /// A saved depth on the scope stack. This is necessary because
  123. /// pushing scopes onto the stack invalidates iterators.
  124. class stable_iterator {
  125. friend class EHScopeStack;
  126. /// Offset from StartOfData to EndOfBuffer.
  127. ptrdiff_t Size;
  128. stable_iterator(ptrdiff_t Size) : Size(Size) {}
  129. public:
  130. static stable_iterator invalid() { return stable_iterator(-1); }
  131. stable_iterator() : Size(-1) {}
  132. bool isValid() const { return Size >= 0; }
  133. /// Returns true if this scope encloses I.
  134. /// Returns false if I is invalid.
  135. /// This scope must be valid.
  136. bool encloses(stable_iterator I) const { return Size <= I.Size; }
  137. /// Returns true if this scope strictly encloses I: that is,
  138. /// if it encloses I and is not I.
  139. /// Returns false is I is invalid.
  140. /// This scope must be valid.
  141. bool strictlyEncloses(stable_iterator I) const { return Size < I.Size; }
  142. friend bool operator==(stable_iterator A, stable_iterator B) {
  143. return A.Size == B.Size;
  144. }
  145. friend bool operator!=(stable_iterator A, stable_iterator B) {
  146. return A.Size != B.Size;
  147. }
  148. };
  149. /// Information for lazily generating a cleanup. Subclasses must be
  150. /// POD-like: cleanups will not be destructed, and they will be
  151. /// allocated on the cleanup stack and freely copied and moved
  152. /// around.
  153. ///
  154. /// Cleanup implementations should generally be declared in an
  155. /// anonymous namespace.
  156. class Cleanup {
  157. public:
  158. // Anchor the construction vtable. We use the destructor because
  159. // gcc gives an obnoxious warning if there are virtual methods
  160. // with an accessible non-virtual destructor. Unfortunately,
  161. // declaring this destructor makes it non-trivial, but there
  162. // doesn't seem to be any other way around this warning.
  163. //
  164. // This destructor will never be called.
  165. virtual ~Cleanup();
  166. /// Emit the cleanup. For normal cleanups, this is run in the
  167. /// same EH context as when the cleanup was pushed, i.e. the
  168. /// immediately-enclosing context of the cleanup scope. For
  169. /// EH cleanups, this is run in a terminate context.
  170. ///
  171. // \param IsForEHCleanup true if this is for an EH cleanup, false
  172. /// if for a normal cleanup.
  173. virtual void Emit(CodeGenFunction &CGF, bool IsForEHCleanup) = 0;
  174. };
  175. /// UnconditionalCleanupN stores its N parameters and just passes
  176. /// them to the real cleanup function.
  177. template <class T, class A0>
  178. class UnconditionalCleanup1 : public Cleanup {
  179. A0 a0;
  180. public:
  181. UnconditionalCleanup1(A0 a0) : a0(a0) {}
  182. void Emit(CodeGenFunction &CGF, bool IsForEHCleanup) {
  183. T::Emit(CGF, IsForEHCleanup, a0);
  184. }
  185. };
  186. template <class T, class A0, class A1>
  187. class UnconditionalCleanup2 : public Cleanup {
  188. A0 a0; A1 a1;
  189. public:
  190. UnconditionalCleanup2(A0 a0, A1 a1) : a0(a0), a1(a1) {}
  191. void Emit(CodeGenFunction &CGF, bool IsForEHCleanup) {
  192. T::Emit(CGF, IsForEHCleanup, a0, a1);
  193. }
  194. };
  195. /// ConditionalCleanupN stores the saved form of its N parameters,
  196. /// then restores them and performs the cleanup.
  197. template <class T, class A0>
  198. class ConditionalCleanup1 : public Cleanup {
  199. typedef typename DominatingValue<A0>::saved_type A0_saved;
  200. A0_saved a0_saved;
  201. void Emit(CodeGenFunction &CGF, bool IsForEHCleanup) {
  202. A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved);
  203. T::Emit(CGF, IsForEHCleanup, a0);
  204. }
  205. public:
  206. ConditionalCleanup1(A0_saved a0)
  207. : a0_saved(a0) {}
  208. };
  209. template <class T, class A0, class A1>
  210. class ConditionalCleanup2 : public Cleanup {
  211. typedef typename DominatingValue<A0>::saved_type A0_saved;
  212. typedef typename DominatingValue<A1>::saved_type A1_saved;
  213. A0_saved a0_saved;
  214. A1_saved a1_saved;
  215. void Emit(CodeGenFunction &CGF, bool IsForEHCleanup) {
  216. A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved);
  217. A1 a1 = DominatingValue<A1>::restore(CGF, a1_saved);
  218. T::Emit(CGF, IsForEHCleanup, a0, a1);
  219. }
  220. public:
  221. ConditionalCleanup2(A0_saved a0, A1_saved a1)
  222. : a0_saved(a0), a1_saved(a1) {}
  223. };
  224. private:
  225. // The implementation for this class is in CGException.h and
  226. // CGException.cpp; the definition is here because it's used as a
  227. // member of CodeGenFunction.
  228. /// The start of the scope-stack buffer, i.e. the allocated pointer
  229. /// for the buffer. All of these pointers are either simultaneously
  230. /// null or simultaneously valid.
  231. char *StartOfBuffer;
  232. /// The end of the buffer.
  233. char *EndOfBuffer;
  234. /// The first valid entry in the buffer.
  235. char *StartOfData;
  236. /// The innermost normal cleanup on the stack.
  237. stable_iterator InnermostNormalCleanup;
  238. /// The innermost EH cleanup on the stack.
  239. stable_iterator InnermostEHCleanup;
  240. /// The number of catches on the stack.
  241. unsigned CatchDepth;
  242. /// The current EH destination index. Reset to FirstCatchIndex
  243. /// whenever the last EH cleanup is popped.
  244. unsigned NextEHDestIndex;
  245. enum { FirstEHDestIndex = 1 };
  246. /// The current set of branch fixups. A branch fixup is a jump to
  247. /// an as-yet unemitted label, i.e. a label for which we don't yet
  248. /// know the EH stack depth. Whenever we pop a cleanup, we have
  249. /// to thread all the current branch fixups through it.
  250. ///
  251. /// Fixups are recorded as the Use of the respective branch or
  252. /// switch statement. The use points to the final destination.
  253. /// When popping out of a cleanup, these uses are threaded through
  254. /// the cleanup and adjusted to point to the new cleanup.
  255. ///
  256. /// Note that branches are allowed to jump into protected scopes
  257. /// in certain situations; e.g. the following code is legal:
  258. /// struct A { ~A(); }; // trivial ctor, non-trivial dtor
  259. /// goto foo;
  260. /// A a;
  261. /// foo:
  262. /// bar();
  263. llvm::SmallVector<BranchFixup, 8> BranchFixups;
  264. char *allocate(size_t Size);
  265. void *pushCleanup(CleanupKind K, size_t DataSize);
  266. public:
  267. EHScopeStack() : StartOfBuffer(0), EndOfBuffer(0), StartOfData(0),
  268. InnermostNormalCleanup(stable_end()),
  269. InnermostEHCleanup(stable_end()),
  270. CatchDepth(0), NextEHDestIndex(FirstEHDestIndex) {}
  271. ~EHScopeStack() { delete[] StartOfBuffer; }
  272. // Variadic templates would make this not terrible.
  273. /// Push a lazily-created cleanup on the stack.
  274. template <class T>
  275. void pushCleanup(CleanupKind Kind) {
  276. void *Buffer = pushCleanup(Kind, sizeof(T));
  277. Cleanup *Obj = new(Buffer) T();
  278. (void) Obj;
  279. }
  280. /// Push a lazily-created cleanup on the stack.
  281. template <class T, class A0>
  282. void pushCleanup(CleanupKind Kind, A0 a0) {
  283. void *Buffer = pushCleanup(Kind, sizeof(T));
  284. Cleanup *Obj = new(Buffer) T(a0);
  285. (void) Obj;
  286. }
  287. /// Push a lazily-created cleanup on the stack.
  288. template <class T, class A0, class A1>
  289. void pushCleanup(CleanupKind Kind, A0 a0, A1 a1) {
  290. void *Buffer = pushCleanup(Kind, sizeof(T));
  291. Cleanup *Obj = new(Buffer) T(a0, a1);
  292. (void) Obj;
  293. }
  294. /// Push a lazily-created cleanup on the stack.
  295. template <class T, class A0, class A1, class A2>
  296. void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2) {
  297. void *Buffer = pushCleanup(Kind, sizeof(T));
  298. Cleanup *Obj = new(Buffer) T(a0, a1, a2);
  299. (void) Obj;
  300. }
  301. /// Push a lazily-created cleanup on the stack.
  302. template <class T, class A0, class A1, class A2, class A3>
  303. void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3) {
  304. void *Buffer = pushCleanup(Kind, sizeof(T));
  305. Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3);
  306. (void) Obj;
  307. }
  308. /// Push a lazily-created cleanup on the stack.
  309. template <class T, class A0, class A1, class A2, class A3, class A4>
  310. void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) {
  311. void *Buffer = pushCleanup(Kind, sizeof(T));
  312. Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3, a4);
  313. (void) Obj;
  314. }
  315. // Feel free to add more variants of the following:
  316. /// Push a cleanup with non-constant storage requirements on the
  317. /// stack. The cleanup type must provide an additional static method:
  318. /// static size_t getExtraSize(size_t);
  319. /// The argument to this method will be the value N, which will also
  320. /// be passed as the first argument to the constructor.
  321. ///
  322. /// The data stored in the extra storage must obey the same
  323. /// restrictions as normal cleanup member data.
  324. ///
  325. /// The pointer returned from this method is valid until the cleanup
  326. /// stack is modified.
  327. template <class T, class A0, class A1, class A2>
  328. T *pushCleanupWithExtra(CleanupKind Kind, size_t N, A0 a0, A1 a1, A2 a2) {
  329. void *Buffer = pushCleanup(Kind, sizeof(T) + T::getExtraSize(N));
  330. return new (Buffer) T(N, a0, a1, a2);
  331. }
  332. /// Pops a cleanup scope off the stack. This should only be called
  333. /// by CodeGenFunction::PopCleanupBlock.
  334. void popCleanup();
  335. /// Push a set of catch handlers on the stack. The catch is
  336. /// uninitialized and will need to have the given number of handlers
  337. /// set on it.
  338. class EHCatchScope *pushCatch(unsigned NumHandlers);
  339. /// Pops a catch scope off the stack.
  340. void popCatch();
  341. /// Push an exceptions filter on the stack.
  342. class EHFilterScope *pushFilter(unsigned NumFilters);
  343. /// Pops an exceptions filter off the stack.
  344. void popFilter();
  345. /// Push a terminate handler on the stack.
  346. void pushTerminate();
  347. /// Pops a terminate handler off the stack.
  348. void popTerminate();
  349. /// Determines whether the exception-scopes stack is empty.
  350. bool empty() const { return StartOfData == EndOfBuffer; }
  351. bool requiresLandingPad() const {
  352. return (CatchDepth || hasEHCleanups());
  353. }
  354. /// Determines whether there are any normal cleanups on the stack.
  355. bool hasNormalCleanups() const {
  356. return InnermostNormalCleanup != stable_end();
  357. }
  358. /// Returns the innermost normal cleanup on the stack, or
  359. /// stable_end() if there are no normal cleanups.
  360. stable_iterator getInnermostNormalCleanup() const {
  361. return InnermostNormalCleanup;
  362. }
  363. stable_iterator getInnermostActiveNormalCleanup() const; // CGException.h
  364. /// Determines whether there are any EH cleanups on the stack.
  365. bool hasEHCleanups() const {
  366. return InnermostEHCleanup != stable_end();
  367. }
  368. /// Returns the innermost EH cleanup on the stack, or stable_end()
  369. /// if there are no EH cleanups.
  370. stable_iterator getInnermostEHCleanup() const {
  371. return InnermostEHCleanup;
  372. }
  373. stable_iterator getInnermostActiveEHCleanup() const; // CGException.h
  374. /// An unstable reference to a scope-stack depth. Invalidated by
  375. /// pushes but not pops.
  376. class iterator;
  377. /// Returns an iterator pointing to the innermost EH scope.
  378. iterator begin() const;
  379. /// Returns an iterator pointing to the outermost EH scope.
  380. iterator end() const;
  381. /// Create a stable reference to the top of the EH stack. The
  382. /// returned reference is valid until that scope is popped off the
  383. /// stack.
  384. stable_iterator stable_begin() const {
  385. return stable_iterator(EndOfBuffer - StartOfData);
  386. }
  387. /// Create a stable reference to the bottom of the EH stack.
  388. static stable_iterator stable_end() {
  389. return stable_iterator(0);
  390. }
  391. /// Translates an iterator into a stable_iterator.
  392. stable_iterator stabilize(iterator it) const;
  393. /// Finds the nearest cleanup enclosing the given iterator.
  394. /// Returns stable_iterator::invalid() if there are no such cleanups.
  395. stable_iterator getEnclosingEHCleanup(iterator it) const;
  396. /// Turn a stable reference to a scope depth into a unstable pointer
  397. /// to the EH stack.
  398. iterator find(stable_iterator save) const;
  399. /// Removes the cleanup pointed to by the given stable_iterator.
  400. void removeCleanup(stable_iterator save);
  401. /// Add a branch fixup to the current cleanup scope.
  402. BranchFixup &addBranchFixup() {
  403. assert(hasNormalCleanups() && "adding fixup in scope without cleanups");
  404. BranchFixups.push_back(BranchFixup());
  405. return BranchFixups.back();
  406. }
  407. unsigned getNumBranchFixups() const { return BranchFixups.size(); }
  408. BranchFixup &getBranchFixup(unsigned I) {
  409. assert(I < getNumBranchFixups());
  410. return BranchFixups[I];
  411. }
  412. /// Pops lazily-removed fixups from the end of the list. This
  413. /// should only be called by procedures which have just popped a
  414. /// cleanup or resolved one or more fixups.
  415. void popNullFixups();
  416. /// Clears the branch-fixups list. This should only be called by
  417. /// ResolveAllBranchFixups.
  418. void clearFixups() { BranchFixups.clear(); }
  419. /// Gets the next EH destination index.
  420. unsigned getNextEHDestIndex() { return NextEHDestIndex++; }
  421. };
  422. /// CodeGenFunction - This class organizes the per-function state that is used
  423. /// while generating LLVM code.
  424. class CodeGenFunction : public CodeGenTypeCache {
  425. CodeGenFunction(const CodeGenFunction&); // DO NOT IMPLEMENT
  426. void operator=(const CodeGenFunction&); // DO NOT IMPLEMENT
  427. friend class CGCXXABI;
  428. public:
  429. /// A jump destination is an abstract label, branching to which may
  430. /// require a jump out through normal cleanups.
  431. struct JumpDest {
  432. JumpDest() : Block(0), ScopeDepth(), Index(0) {}
  433. JumpDest(llvm::BasicBlock *Block,
  434. EHScopeStack::stable_iterator Depth,
  435. unsigned Index)
  436. : Block(Block), ScopeDepth(Depth), Index(Index) {}
  437. bool isValid() const { return Block != 0; }
  438. llvm::BasicBlock *getBlock() const { return Block; }
  439. EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
  440. unsigned getDestIndex() const { return Index; }
  441. private:
  442. llvm::BasicBlock *Block;
  443. EHScopeStack::stable_iterator ScopeDepth;
  444. unsigned Index;
  445. };
  446. /// An unwind destination is an abstract label, branching to which
  447. /// may require a jump out through EH cleanups.
  448. struct UnwindDest {
  449. UnwindDest() : Block(0), ScopeDepth(), Index(0) {}
  450. UnwindDest(llvm::BasicBlock *Block,
  451. EHScopeStack::stable_iterator Depth,
  452. unsigned Index)
  453. : Block(Block), ScopeDepth(Depth), Index(Index) {}
  454. bool isValid() const { return Block != 0; }
  455. llvm::BasicBlock *getBlock() const { return Block; }
  456. EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
  457. unsigned getDestIndex() const { return Index; }
  458. private:
  459. llvm::BasicBlock *Block;
  460. EHScopeStack::stable_iterator ScopeDepth;
  461. unsigned Index;
  462. };
  463. CodeGenModule &CGM; // Per-module state.
  464. const TargetInfo &Target;
  465. typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
  466. CGBuilderTy Builder;
  467. /// CurFuncDecl - Holds the Decl for the current function or ObjC method.
  468. /// This excludes BlockDecls.
  469. const Decl *CurFuncDecl;
  470. /// CurCodeDecl - This is the inner-most code context, which includes blocks.
  471. const Decl *CurCodeDecl;
  472. const CGFunctionInfo *CurFnInfo;
  473. QualType FnRetTy;
  474. llvm::Function *CurFn;
  475. /// CurGD - The GlobalDecl for the current function being compiled.
  476. GlobalDecl CurGD;
  477. /// ReturnBlock - Unified return block.
  478. JumpDest ReturnBlock;
  479. /// ReturnValue - The temporary alloca to hold the return value. This is null
  480. /// iff the function has no return value.
  481. llvm::Value *ReturnValue;
  482. /// RethrowBlock - Unified rethrow block.
  483. UnwindDest RethrowBlock;
  484. /// AllocaInsertPoint - This is an instruction in the entry block before which
  485. /// we prefer to insert allocas.
  486. llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
  487. bool CatchUndefined;
  488. const CodeGen::CGBlockInfo *BlockInfo;
  489. llvm::Value *BlockPointer;
  490. /// \brief A mapping from NRVO variables to the flags used to indicate
  491. /// when the NRVO has been applied to this variable.
  492. llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
  493. EHScopeStack EHStack;
  494. /// i32s containing the indexes of the cleanup destinations.
  495. llvm::AllocaInst *NormalCleanupDest;
  496. llvm::AllocaInst *EHCleanupDest;
  497. unsigned NextCleanupDestIndex;
  498. /// The exception slot. All landing pads write the current
  499. /// exception pointer into this alloca.
  500. llvm::Value *ExceptionSlot;
  501. /// Emits a landing pad for the current EH stack.
  502. llvm::BasicBlock *EmitLandingPad();
  503. llvm::BasicBlock *getInvokeDestImpl();
  504. /// Set up the last cleaup that was pushed as a conditional
  505. /// full-expression cleanup.
  506. void initFullExprCleanup();
  507. template <class T>
  508. typename DominatingValue<T>::saved_type saveValueInCond(T value) {
  509. return DominatingValue<T>::save(*this, value);
  510. }
  511. public:
  512. /// ObjCEHValueStack - Stack of Objective-C exception values, used for
  513. /// rethrows.
  514. llvm::SmallVector<llvm::Value*, 8> ObjCEHValueStack;
  515. // A struct holding information about a finally block's IR
  516. // generation. For now, doesn't actually hold anything.
  517. struct FinallyInfo {
  518. };
  519. FinallyInfo EnterFinallyBlock(const Stmt *Stmt,
  520. llvm::Constant *BeginCatchFn,
  521. llvm::Constant *EndCatchFn,
  522. llvm::Constant *RethrowFn);
  523. void ExitFinallyBlock(FinallyInfo &FinallyInfo);
  524. /// pushFullExprCleanup - Push a cleanup to be run at the end of the
  525. /// current full-expression. Safe against the possibility that
  526. /// we're currently inside a conditionally-evaluated expression.
  527. template <class T, class A0>
  528. void pushFullExprCleanup(CleanupKind kind, A0 a0) {
  529. // If we're not in a conditional branch, or if none of the
  530. // arguments requires saving, then use the unconditional cleanup.
  531. if (!isInConditionalBranch()) {
  532. typedef EHScopeStack::UnconditionalCleanup1<T, A0> CleanupType;
  533. return EHStack.pushCleanup<CleanupType>(kind, a0);
  534. }
  535. typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0);
  536. typedef EHScopeStack::ConditionalCleanup1<T, A0> CleanupType;
  537. EHStack.pushCleanup<CleanupType>(kind, a0_saved);
  538. initFullExprCleanup();
  539. }
  540. /// pushFullExprCleanup - Push a cleanup to be run at the end of the
  541. /// current full-expression. Safe against the possibility that
  542. /// we're currently inside a conditionally-evaluated expression.
  543. template <class T, class A0, class A1>
  544. void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1) {
  545. // If we're not in a conditional branch, or if none of the
  546. // arguments requires saving, then use the unconditional cleanup.
  547. if (!isInConditionalBranch()) {
  548. typedef EHScopeStack::UnconditionalCleanup2<T, A0, A1> CleanupType;
  549. return EHStack.pushCleanup<CleanupType>(kind, a0, a1);
  550. }
  551. typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0);
  552. typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1);
  553. typedef EHScopeStack::ConditionalCleanup2<T, A0, A1> CleanupType;
  554. EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved);
  555. initFullExprCleanup();
  556. }
  557. /// PushDestructorCleanup - Push a cleanup to call the
  558. /// complete-object destructor of an object of the given type at the
  559. /// given address. Does nothing if T is not a C++ class type with a
  560. /// non-trivial destructor.
  561. void PushDestructorCleanup(QualType T, llvm::Value *Addr);
  562. /// PushDestructorCleanup - Push a cleanup to call the
  563. /// complete-object variant of the given destructor on the object at
  564. /// the given address.
  565. void PushDestructorCleanup(const CXXDestructorDecl *Dtor,
  566. llvm::Value *Addr);
  567. /// PopCleanupBlock - Will pop the cleanup entry on the stack and
  568. /// process all branch fixups.
  569. void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
  570. /// DeactivateCleanupBlock - Deactivates the given cleanup block.
  571. /// The block cannot be reactivated. Pops it if it's the top of the
  572. /// stack.
  573. void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup);
  574. /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
  575. /// Cannot be used to resurrect a deactivated cleanup.
  576. void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup);
  577. /// \brief Enters a new scope for capturing cleanups, all of which
  578. /// will be executed once the scope is exited.
  579. class RunCleanupsScope {
  580. CodeGenFunction& CGF;
  581. EHScopeStack::stable_iterator CleanupStackDepth;
  582. bool OldDidCallStackSave;
  583. bool PerformCleanup;
  584. RunCleanupsScope(const RunCleanupsScope &); // DO NOT IMPLEMENT
  585. RunCleanupsScope &operator=(const RunCleanupsScope &); // DO NOT IMPLEMENT
  586. public:
  587. /// \brief Enter a new cleanup scope.
  588. explicit RunCleanupsScope(CodeGenFunction &CGF)
  589. : CGF(CGF), PerformCleanup(true)
  590. {
  591. CleanupStackDepth = CGF.EHStack.stable_begin();
  592. OldDidCallStackSave = CGF.DidCallStackSave;
  593. CGF.DidCallStackSave = false;
  594. }
  595. /// \brief Exit this cleanup scope, emitting any accumulated
  596. /// cleanups.
  597. ~RunCleanupsScope() {
  598. if (PerformCleanup) {
  599. CGF.DidCallStackSave = OldDidCallStackSave;
  600. CGF.PopCleanupBlocks(CleanupStackDepth);
  601. }
  602. }
  603. /// \brief Determine whether this scope requires any cleanups.
  604. bool requiresCleanups() const {
  605. return CGF.EHStack.stable_begin() != CleanupStackDepth;
  606. }
  607. /// \brief Force the emission of cleanups now, instead of waiting
  608. /// until this object is destroyed.
  609. void ForceCleanup() {
  610. assert(PerformCleanup && "Already forced cleanup");
  611. CGF.DidCallStackSave = OldDidCallStackSave;
  612. CGF.PopCleanupBlocks(CleanupStackDepth);
  613. PerformCleanup = false;
  614. }
  615. };
  616. /// PopCleanupBlocks - Takes the old cleanup stack size and emits
  617. /// the cleanup blocks that have been added.
  618. void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize);
  619. void ResolveBranchFixups(llvm::BasicBlock *Target);
  620. /// The given basic block lies in the current EH scope, but may be a
  621. /// target of a potentially scope-crossing jump; get a stable handle
  622. /// to which we can perform this jump later.
  623. JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
  624. return JumpDest(Target,
  625. EHStack.getInnermostNormalCleanup(),
  626. NextCleanupDestIndex++);
  627. }
  628. /// The given basic block lies in the current EH scope, but may be a
  629. /// target of a potentially scope-crossing jump; get a stable handle
  630. /// to which we can perform this jump later.
  631. JumpDest getJumpDestInCurrentScope(llvm::StringRef Name = llvm::StringRef()) {
  632. return getJumpDestInCurrentScope(createBasicBlock(Name));
  633. }
  634. /// EmitBranchThroughCleanup - Emit a branch from the current insert
  635. /// block through the normal cleanup handling code (if any) and then
  636. /// on to \arg Dest.
  637. void EmitBranchThroughCleanup(JumpDest Dest);
  638. /// EmitBranchThroughEHCleanup - Emit a branch from the current
  639. /// insert block through the EH cleanup handling code (if any) and
  640. /// then on to \arg Dest.
  641. void EmitBranchThroughEHCleanup(UnwindDest Dest);
  642. /// getRethrowDest - Returns the unified outermost-scope rethrow
  643. /// destination.
  644. UnwindDest getRethrowDest();
  645. /// An object to manage conditionally-evaluated expressions.
  646. class ConditionalEvaluation {
  647. llvm::BasicBlock *StartBB;
  648. public:
  649. ConditionalEvaluation(CodeGenFunction &CGF)
  650. : StartBB(CGF.Builder.GetInsertBlock()) {}
  651. void begin(CodeGenFunction &CGF) {
  652. assert(CGF.OutermostConditional != this);
  653. if (!CGF.OutermostConditional)
  654. CGF.OutermostConditional = this;
  655. }
  656. void end(CodeGenFunction &CGF) {
  657. assert(CGF.OutermostConditional != 0);
  658. if (CGF.OutermostConditional == this)
  659. CGF.OutermostConditional = 0;
  660. }
  661. /// Returns a block which will be executed prior to each
  662. /// evaluation of the conditional code.
  663. llvm::BasicBlock *getStartingBlock() const {
  664. return StartBB;
  665. }
  666. };
  667. /// isInConditionalBranch - Return true if we're currently emitting
  668. /// one branch or the other of a conditional expression.
  669. bool isInConditionalBranch() const { return OutermostConditional != 0; }
  670. /// An RAII object to record that we're evaluating a statement
  671. /// expression.
  672. class StmtExprEvaluation {
  673. CodeGenFunction &CGF;
  674. /// We have to save the outermost conditional: cleanups in a
  675. /// statement expression aren't conditional just because the
  676. /// StmtExpr is.
  677. ConditionalEvaluation *SavedOutermostConditional;
  678. public:
  679. StmtExprEvaluation(CodeGenFunction &CGF)
  680. : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) {
  681. CGF.OutermostConditional = 0;
  682. }
  683. ~StmtExprEvaluation() {
  684. CGF.OutermostConditional = SavedOutermostConditional;
  685. CGF.EnsureInsertPoint();
  686. }
  687. };
  688. /// An object which temporarily prevents a value from being
  689. /// destroyed by aggressive peephole optimizations that assume that
  690. /// all uses of a value have been realized in the IR.
  691. class PeepholeProtection {
  692. llvm::Instruction *Inst;
  693. friend class CodeGenFunction;
  694. public:
  695. PeepholeProtection() : Inst(0) {}
  696. };
  697. /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
  698. class OpaqueValueMapping {
  699. CodeGenFunction &CGF;
  700. const OpaqueValueExpr *OpaqueValue;
  701. bool BoundLValue;
  702. CodeGenFunction::PeepholeProtection Protection;
  703. public:
  704. static bool shouldBindAsLValue(const Expr *expr) {
  705. return expr->isGLValue() || expr->getType()->isRecordType();
  706. }
  707. /// Build the opaque value mapping for the given conditional
  708. /// operator if it's the GNU ?: extension. This is a common
  709. /// enough pattern that the convenience operator is really
  710. /// helpful.
  711. ///
  712. OpaqueValueMapping(CodeGenFunction &CGF,
  713. const AbstractConditionalOperator *op) : CGF(CGF) {
  714. if (isa<ConditionalOperator>(op)) {
  715. OpaqueValue = 0;
  716. BoundLValue = false;
  717. return;
  718. }
  719. const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op);
  720. init(e->getOpaqueValue(), e->getCommon());
  721. }
  722. OpaqueValueMapping(CodeGenFunction &CGF,
  723. const OpaqueValueExpr *opaqueValue,
  724. LValue lvalue)
  725. : CGF(CGF), OpaqueValue(opaqueValue), BoundLValue(true) {
  726. assert(opaqueValue && "no opaque value expression!");
  727. assert(shouldBindAsLValue(opaqueValue));
  728. initLValue(lvalue);
  729. }
  730. OpaqueValueMapping(CodeGenFunction &CGF,
  731. const OpaqueValueExpr *opaqueValue,
  732. RValue rvalue)
  733. : CGF(CGF), OpaqueValue(opaqueValue), BoundLValue(false) {
  734. assert(opaqueValue && "no opaque value expression!");
  735. assert(!shouldBindAsLValue(opaqueValue));
  736. initRValue(rvalue);
  737. }
  738. void pop() {
  739. assert(OpaqueValue && "mapping already popped!");
  740. popImpl();
  741. OpaqueValue = 0;
  742. }
  743. ~OpaqueValueMapping() {
  744. if (OpaqueValue) popImpl();
  745. }
  746. private:
  747. void popImpl() {
  748. if (BoundLValue)
  749. CGF.OpaqueLValues.erase(OpaqueValue);
  750. else {
  751. CGF.OpaqueRValues.erase(OpaqueValue);
  752. CGF.unprotectFromPeepholes(Protection);
  753. }
  754. }
  755. void init(const OpaqueValueExpr *ov, const Expr *e) {
  756. OpaqueValue = ov;
  757. BoundLValue = shouldBindAsLValue(ov);
  758. assert(BoundLValue == shouldBindAsLValue(e)
  759. && "inconsistent expression value kinds!");
  760. if (BoundLValue)
  761. initLValue(CGF.EmitLValue(e));
  762. else
  763. initRValue(CGF.EmitAnyExpr(e));
  764. }
  765. void initLValue(const LValue &lv) {
  766. CGF.OpaqueLValues.insert(std::make_pair(OpaqueValue, lv));
  767. }
  768. void initRValue(const RValue &rv) {
  769. // Work around an extremely aggressive peephole optimization in
  770. // EmitScalarConversion which assumes that all other uses of a
  771. // value are extant.
  772. Protection = CGF.protectFromPeepholes(rv);
  773. CGF.OpaqueRValues.insert(std::make_pair(OpaqueValue, rv));
  774. }
  775. };
  776. /// getByrefValueFieldNumber - Given a declaration, returns the LLVM field
  777. /// number that holds the value.
  778. unsigned getByRefValueLLVMField(const ValueDecl *VD) const;
  779. /// BuildBlockByrefAddress - Computes address location of the
  780. /// variable which is declared as __block.
  781. llvm::Value *BuildBlockByrefAddress(llvm::Value *BaseAddr,
  782. const VarDecl *V);
  783. private:
  784. CGDebugInfo *DebugInfo;
  785. bool DisableDebugInfo;
  786. /// IndirectBranch - The first time an indirect goto is seen we create a block
  787. /// with an indirect branch. Every time we see the address of a label taken,
  788. /// we add the label to the indirect goto. Every subsequent indirect goto is
  789. /// codegen'd as a jump to the IndirectBranch's basic block.
  790. llvm::IndirectBrInst *IndirectBranch;
  791. /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
  792. /// decls.
  793. typedef llvm::DenseMap<const Decl*, llvm::Value*> DeclMapTy;
  794. DeclMapTy LocalDeclMap;
  795. /// LabelMap - This keeps track of the LLVM basic block for each C label.
  796. llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap;
  797. // BreakContinueStack - This keeps track of where break and continue
  798. // statements should jump to.
  799. struct BreakContinue {
  800. BreakContinue(JumpDest Break, JumpDest Continue)
  801. : BreakBlock(Break), ContinueBlock(Continue) {}
  802. JumpDest BreakBlock;
  803. JumpDest ContinueBlock;
  804. };
  805. llvm::SmallVector<BreakContinue, 8> BreakContinueStack;
  806. /// SwitchInsn - This is nearest current switch instruction. It is null if if
  807. /// current context is not in a switch.
  808. llvm::SwitchInst *SwitchInsn;
  809. /// CaseRangeBlock - This block holds if condition check for last case
  810. /// statement range in current switch instruction.
  811. llvm::BasicBlock *CaseRangeBlock;
  812. /// OpaqueLValues - Keeps track of the current set of opaque value
  813. /// expressions.
  814. llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
  815. llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
  816. // VLASizeMap - This keeps track of the associated size for each VLA type.
  817. // We track this by the size expression rather than the type itself because
  818. // in certain situations, like a const qualifier applied to an VLA typedef,
  819. // multiple VLA types can share the same size expression.
  820. // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
  821. // enter/leave scopes.
  822. llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
  823. /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
  824. /// calling llvm.stacksave for multiple VLAs in the same scope.
  825. bool DidCallStackSave;
  826. /// A block containing a single 'unreachable' instruction. Created
  827. /// lazily by getUnreachableBlock().
  828. llvm::BasicBlock *UnreachableBlock;
  829. /// CXXThisDecl - When generating code for a C++ member function,
  830. /// this will hold the implicit 'this' declaration.
  831. ImplicitParamDecl *CXXThisDecl;
  832. llvm::Value *CXXThisValue;
  833. /// CXXVTTDecl - When generating code for a base object constructor or
  834. /// base object destructor with virtual bases, this will hold the implicit
  835. /// VTT parameter.
  836. ImplicitParamDecl *CXXVTTDecl;
  837. llvm::Value *CXXVTTValue;
  838. /// OutermostConditional - Points to the outermost active
  839. /// conditional control. This is used so that we know if a
  840. /// temporary should be destroyed conditionally.
  841. ConditionalEvaluation *OutermostConditional;
  842. /// ByrefValueInfoMap - For each __block variable, contains a pair of the LLVM
  843. /// type as well as the field number that contains the actual data.
  844. llvm::DenseMap<const ValueDecl *, std::pair<const llvm::Type *,
  845. unsigned> > ByRefValueInfo;
  846. llvm::BasicBlock *TerminateLandingPad;
  847. llvm::BasicBlock *TerminateHandler;
  848. llvm::BasicBlock *TrapBB;
  849. public:
  850. CodeGenFunction(CodeGenModule &cgm);
  851. CodeGenTypes &getTypes() const { return CGM.getTypes(); }
  852. ASTContext &getContext() const;
  853. CGDebugInfo *getDebugInfo() {
  854. if (DisableDebugInfo)
  855. return NULL;
  856. return DebugInfo;
  857. }
  858. void disableDebugInfo() { DisableDebugInfo = true; }
  859. void enableDebugInfo() { DisableDebugInfo = false; }
  860. const LangOptions &getLangOptions() const { return CGM.getLangOptions(); }
  861. /// Returns a pointer to the function's exception object slot, which
  862. /// is assigned in every landing pad.
  863. llvm::Value *getExceptionSlot();
  864. llvm::Value *getNormalCleanupDestSlot();
  865. llvm::Value *getEHCleanupDestSlot();
  866. llvm::BasicBlock *getUnreachableBlock() {
  867. if (!UnreachableBlock) {
  868. UnreachableBlock = createBasicBlock("unreachable");
  869. new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
  870. }
  871. return UnreachableBlock;
  872. }
  873. llvm::BasicBlock *getInvokeDest() {
  874. if (!EHStack.requiresLandingPad()) return 0;
  875. return getInvokeDestImpl();
  876. }
  877. llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
  878. //===--------------------------------------------------------------------===//
  879. // Objective-C
  880. //===--------------------------------------------------------------------===//
  881. void GenerateObjCMethod(const ObjCMethodDecl *OMD);
  882. void StartObjCMethod(const ObjCMethodDecl *MD,
  883. const ObjCContainerDecl *CD);
  884. /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
  885. void GenerateObjCGetter(ObjCImplementationDecl *IMP,
  886. const ObjCPropertyImplDecl *PID);
  887. void GenerateObjCGetterBody(ObjCIvarDecl *Ivar, bool IsAtomic, bool IsStrong);
  888. void GenerateObjCAtomicSetterBody(ObjCMethodDecl *OMD,
  889. ObjCIvarDecl *Ivar);
  890. void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
  891. ObjCMethodDecl *MD, bool ctor);
  892. /// GenerateObjCSetter - Synthesize an Objective-C property setter function
  893. /// for the given property.
  894. void GenerateObjCSetter(ObjCImplementationDecl *IMP,
  895. const ObjCPropertyImplDecl *PID);
  896. bool IndirectObjCSetterArg(const CGFunctionInfo &FI);
  897. bool IvarTypeWithAggrGCObjects(QualType Ty);
  898. //===--------------------------------------------------------------------===//
  899. // Block Bits
  900. //===--------------------------------------------------------------------===//
  901. llvm::Value *EmitBlockLiteral(const BlockExpr *);
  902. llvm::Constant *BuildDescriptorBlockDecl(const BlockExpr *,
  903. const CGBlockInfo &Info,
  904. const llvm::StructType *,
  905. llvm::Constant *BlockVarLayout);
  906. llvm::Function *GenerateBlockFunction(GlobalDecl GD,
  907. const CGBlockInfo &Info,
  908. const Decl *OuterFuncDecl,
  909. const DeclMapTy &ldm);
  910. llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
  911. llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
  912. llvm::Constant *GeneratebyrefCopyHelperFunction(const llvm::Type *,
  913. BlockFieldFlags flags,
  914. const VarDecl *BD);
  915. llvm::Constant *GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
  916. BlockFieldFlags flags,
  917. const VarDecl *BD);
  918. void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags);
  919. llvm::Value *LoadBlockStruct() {
  920. assert(BlockPointer && "no block pointer set!");
  921. return BlockPointer;
  922. }
  923. void AllocateBlockCXXThisPointer(const CXXThisExpr *E);
  924. void AllocateBlockDecl(const BlockDeclRefExpr *E);
  925. llvm::Value *GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
  926. return GetAddrOfBlockDecl(E->getDecl(), E->isByRef());
  927. }
  928. llvm::Value *GetAddrOfBlockDecl(const VarDecl *var, bool ByRef);
  929. const llvm::Type *BuildByRefType(const VarDecl *var);
  930. void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
  931. const CGFunctionInfo &FnInfo);
  932. void StartFunction(GlobalDecl GD, QualType RetTy,
  933. llvm::Function *Fn,
  934. const CGFunctionInfo &FnInfo,
  935. const FunctionArgList &Args,
  936. SourceLocation StartLoc);
  937. void EmitConstructorBody(FunctionArgList &Args);
  938. void EmitDestructorBody(FunctionArgList &Args);
  939. void EmitFunctionBody(FunctionArgList &Args);
  940. /// EmitReturnBlock - Emit the unified return block, trying to avoid its
  941. /// emission when possible.
  942. void EmitReturnBlock();
  943. /// FinishFunction - Complete IR generation of the current function. It is
  944. /// legal to call this function even if there is no current insertion point.
  945. void FinishFunction(SourceLocation EndLoc=SourceLocation());
  946. /// GenerateThunk - Generate a thunk for the given method.
  947. void GenerateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
  948. GlobalDecl GD, const ThunkInfo &Thunk);
  949. void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
  950. FunctionArgList &Args);
  951. /// InitializeVTablePointer - Initialize the vtable pointer of the given
  952. /// subobject.
  953. ///
  954. void InitializeVTablePointer(BaseSubobject Base,
  955. const CXXRecordDecl *NearestVBase,
  956. uint64_t OffsetFromNearestVBase,
  957. llvm::Constant *VTable,
  958. const CXXRecordDecl *VTableClass);
  959. typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
  960. void InitializeVTablePointers(BaseSubobject Base,
  961. const CXXRecordDecl *NearestVBase,
  962. uint64_t OffsetFromNearestVBase,
  963. bool BaseIsNonVirtualPrimaryBase,
  964. llvm::Constant *VTable,
  965. const CXXRecordDecl *VTableClass,
  966. VisitedVirtualBasesSetTy& VBases);
  967. void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
  968. /// GetVTablePtr - Return the Value of the vtable pointer member pointed
  969. /// to by This.
  970. llvm::Value *GetVTablePtr(llvm::Value *This, const llvm::Type *Ty);
  971. /// EnterDtorCleanups - Enter the cleanups necessary to complete the
  972. /// given phase of destruction for a destructor. The end result
  973. /// should call destructors on members and base classes in reverse
  974. /// order of their construction.
  975. void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
  976. /// ShouldInstrumentFunction - Return true if the current function should be
  977. /// instrumented with __cyg_profile_func_* calls
  978. bool ShouldInstrumentFunction();
  979. /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
  980. /// instrumentation function with the current function and the call site, if
  981. /// function instrumentation is enabled.
  982. void EmitFunctionInstrumentation(const char *Fn);
  983. /// EmitMCountInstrumentation - Emit call to .mcount.
  984. void EmitMCountInstrumentation();
  985. /// EmitFunctionProlog - Emit the target specific LLVM code to load the
  986. /// arguments for the given function. This is also responsible for naming the
  987. /// LLVM function arguments.
  988. void EmitFunctionProlog(const CGFunctionInfo &FI,
  989. llvm::Function *Fn,
  990. const FunctionArgList &Args);
  991. /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
  992. /// given temporary.
  993. void EmitFunctionEpilog(const CGFunctionInfo &FI);
  994. /// EmitStartEHSpec - Emit the start of the exception spec.
  995. void EmitStartEHSpec(const Decl *D);
  996. /// EmitEndEHSpec - Emit the end of the exception spec.
  997. void EmitEndEHSpec(const Decl *D);
  998. /// getTerminateLandingPad - Return a landing pad that just calls terminate.
  999. llvm::BasicBlock *getTerminateLandingPad();
  1000. /// getTerminateHandler - Return a handler (not a landing pad, just
  1001. /// a catch handler) that just calls terminate. This is used when
  1002. /// a terminate scope encloses a try.
  1003. llvm::BasicBlock *getTerminateHandler();
  1004. const llvm::Type *ConvertTypeForMem(QualType T);
  1005. const llvm::Type *ConvertType(QualType T);
  1006. const llvm::Type *ConvertType(const TypeDecl *T) {
  1007. return ConvertType(getContext().getTypeDeclType(T));
  1008. }
  1009. /// LoadObjCSelf - Load the value of self. This function is only valid while
  1010. /// generating code for an Objective-C method.
  1011. llvm::Value *LoadObjCSelf();
  1012. /// TypeOfSelfObject - Return type of object that this self represents.
  1013. QualType TypeOfSelfObject();
  1014. /// hasAggregateLLVMType - Return true if the specified AST type will map into
  1015. /// an aggregate LLVM type or is void.
  1016. static bool hasAggregateLLVMType(QualType T);
  1017. /// createBasicBlock - Create an LLVM basic block.
  1018. llvm::BasicBlock *createBasicBlock(llvm::StringRef name = "",
  1019. llvm::Function *parent = 0,
  1020. llvm::BasicBlock *before = 0) {
  1021. #ifdef NDEBUG
  1022. return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before);
  1023. #else
  1024. return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
  1025. #endif
  1026. }
  1027. /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
  1028. /// label maps to.
  1029. JumpDest getJumpDestForLabel(const LabelDecl *S);
  1030. /// SimplifyForwardingBlocks - If the given basic block is only a branch to
  1031. /// another basic block, simplify it. This assumes that no other code could
  1032. /// potentially reference the basic block.
  1033. void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
  1034. /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
  1035. /// adding a fall-through branch from the current insert block if
  1036. /// necessary. It is legal to call this function even if there is no current
  1037. /// insertion point.
  1038. ///
  1039. /// IsFinished - If true, indicates that the caller has finished emitting
  1040. /// branches to the given block and does not expect to emit code into it. This
  1041. /// means the block can be ignored if it is unreachable.
  1042. void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
  1043. /// EmitBranch - Emit a branch to the specified basic block from the current
  1044. /// insert block, taking care to avoid creation of branches from dummy
  1045. /// blocks. It is legal to call this function even if there is no current
  1046. /// insertion point.
  1047. ///
  1048. /// This function clears the current insertion point. The caller should follow
  1049. /// calls to this function with calls to Emit*Block prior to generation new
  1050. /// code.
  1051. void EmitBranch(llvm::BasicBlock *Block);
  1052. /// HaveInsertPoint - True if an insertion point is defined. If not, this
  1053. /// indicates that the current code being emitted is unreachable.
  1054. bool HaveInsertPoint() const {
  1055. return Builder.GetInsertBlock() != 0;
  1056. }
  1057. /// EnsureInsertPoint - Ensure that an insertion point is defined so that
  1058. /// emitted IR has a place to go. Note that by definition, if this function
  1059. /// creates a block then that block is unreachable; callers may do better to
  1060. /// detect when no insertion point is defined and simply skip IR generation.
  1061. void EnsureInsertPoint() {
  1062. if (!HaveInsertPoint())
  1063. EmitBlock(createBasicBlock());
  1064. }
  1065. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  1066. /// specified stmt yet.
  1067. void ErrorUnsupported(const Stmt *S, const char *Type,
  1068. bool OmitOnError=false);
  1069. //===--------------------------------------------------------------------===//
  1070. // Helpers
  1071. //===--------------------------------------------------------------------===//
  1072. LValue MakeAddrLValue(llvm::Value *V, QualType T, unsigned Alignment = 0) {
  1073. return LValue::MakeAddr(V, T, Alignment, getContext(),
  1074. CGM.getTBAAInfo(T));
  1075. }
  1076. /// CreateTempAlloca - This creates a alloca and inserts it into the entry
  1077. /// block. The caller is responsible for setting an appropriate alignment on
  1078. /// the alloca.
  1079. llvm::AllocaInst *CreateTempAlloca(const llvm::Type *Ty,
  1080. const llvm::Twine &Name = "tmp");
  1081. /// InitTempAlloca - Provide an initial value for the given alloca.
  1082. void InitTempAlloca(llvm::AllocaInst *Alloca, llvm::Value *Value);
  1083. /// CreateIRTemp - Create a temporary IR object of the given type, with
  1084. /// appropriate alignment. This routine should only be used when an temporary
  1085. /// value needs to be stored into an alloca (for example, to avoid explicit
  1086. /// PHI construction), but the type is the IR type, not the type appropriate
  1087. /// for storing in memory.
  1088. llvm::AllocaInst *CreateIRTemp(QualType T, const llvm::Twine &Name = "tmp");
  1089. /// CreateMemTemp - Create a temporary memory object of the given type, with
  1090. /// appropriate alignment.
  1091. llvm::AllocaInst *CreateMemTemp(QualType T, const llvm::Twine &Name = "tmp");
  1092. /// CreateAggTemp - Create a temporary memory object for the given
  1093. /// aggregate type.
  1094. AggValueSlot CreateAggTemp(QualType T, const llvm::Twine &Name = "tmp") {
  1095. return AggValueSlot::forAddr(CreateMemTemp(T, Name), false, false);
  1096. }
  1097. /// Emit a cast to void* in the appropriate address space.
  1098. llvm::Value *EmitCastToVoidPtr(llvm::Value *value);
  1099. /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
  1100. /// expression and compare the result against zero, returning an Int1Ty value.
  1101. llvm::Value *EvaluateExprAsBool(const Expr *E);
  1102. /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
  1103. void EmitIgnoredExpr(const Expr *E);
  1104. /// EmitAnyExpr - Emit code to compute the specified expression which can have
  1105. /// any type. The result is returned as an RValue struct. If this is an
  1106. /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
  1107. /// the result should be returned.
  1108. ///
  1109. /// \param IgnoreResult - True if the resulting value isn't used.
  1110. RValue EmitAnyExpr(const Expr *E,
  1111. AggValueSlot AggSlot = AggValueSlot::ignored(),
  1112. bool IgnoreResult = false);
  1113. // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
  1114. // or the value of the expression, depending on how va_list is defined.
  1115. llvm::Value *EmitVAListRef(const Expr *E);
  1116. /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
  1117. /// always be accessible even if no aggregate location is provided.
  1118. RValue EmitAnyExprToTemp(const Expr *E);
  1119. /// EmitAnyExprToMem - Emits the code necessary to evaluate an
  1120. /// arbitrary expression into the given memory location.
  1121. void EmitAnyExprToMem(const Expr *E, llvm::Value *Location,
  1122. bool IsLocationVolatile,
  1123. bool IsInitializer);
  1124. /// EmitExprAsInit - Emits the code necessary to initialize a
  1125. /// location in memory with the given initializer.
  1126. void EmitExprAsInit(const Expr *init, const VarDecl *var,
  1127. llvm::Value *loc, CharUnits alignment,
  1128. bool capturedByInit);
  1129. /// EmitAggregateCopy - Emit an aggrate copy.
  1130. ///
  1131. /// \param isVolatile - True iff either the source or the destination is
  1132. /// volatile.
  1133. void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr,
  1134. QualType EltTy, bool isVolatile=false);
  1135. /// StartBlock - Start new block named N. If insert block is a dummy block
  1136. /// then reuse it.
  1137. void StartBlock(const char *N);
  1138. /// GetAddrOfStaticLocalVar - Return the address of a static local variable.
  1139. llvm::Constant *GetAddrOfStaticLocalVar(const VarDecl *BVD) {
  1140. return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
  1141. }
  1142. /// GetAddrOfLocalVar - Return the address of a local variable.
  1143. llvm::Value *GetAddrOfLocalVar(const VarDecl *VD) {
  1144. llvm::Value *Res = LocalDeclMap[VD];
  1145. assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
  1146. return Res;
  1147. }
  1148. /// getOpaqueLValueMapping - Given an opaque value expression (which
  1149. /// must be mapped to an l-value), return its mapping.
  1150. const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) {
  1151. assert(OpaqueValueMapping::shouldBindAsLValue(e));
  1152. llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
  1153. it = OpaqueLValues.find(e);
  1154. assert(it != OpaqueLValues.end() && "no mapping for opaque value!");
  1155. return it->second;
  1156. }
  1157. /// getOpaqueRValueMapping - Given an opaque value expression (which
  1158. /// must be mapped to an r-value), return its mapping.
  1159. const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) {
  1160. assert(!OpaqueValueMapping::shouldBindAsLValue(e));
  1161. llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
  1162. it = OpaqueRValues.find(e);
  1163. assert(it != OpaqueRValues.end() && "no mapping for opaque value!");
  1164. return it->second;
  1165. }
  1166. /// getAccessedFieldNo - Given an encoded value and a result number, return
  1167. /// the input field number being accessed.
  1168. static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
  1169. llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
  1170. llvm::BasicBlock *GetIndirectGotoBlock();
  1171. /// EmitNullInitialization - Generate code to set a value of the given type to
  1172. /// null, If the type contains data member pointers, they will be initialized
  1173. /// to -1 in accordance with the Itanium C++ ABI.
  1174. void EmitNullInitialization(llvm::Value *DestPtr, QualType Ty);
  1175. // EmitVAArg - Generate code to get an argument from the passed in pointer
  1176. // and update it accordingly. The return value is a pointer to the argument.
  1177. // FIXME: We should be able to get rid of this method and use the va_arg
  1178. // instruction in LLVM instead once it works well enough.
  1179. llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty);
  1180. /// EmitVLASize - Generate code for any VLA size expressions that might occur
  1181. /// in a variably modified type. If Ty is a VLA, will return the value that
  1182. /// corresponds to the size in bytes of the VLA type. Will return 0 otherwise.
  1183. ///
  1184. /// This function can be called with a null (unreachable) insert point.
  1185. llvm::Value *EmitVLASize(QualType Ty);
  1186. // GetVLASize - Returns an LLVM value that corresponds to the size in bytes
  1187. // of a variable length array type.
  1188. llvm::Value *GetVLASize(const VariableArrayType *);
  1189. /// LoadCXXThis - Load the value of 'this'. This function is only valid while
  1190. /// generating code for an C++ member function.
  1191. llvm::Value *LoadCXXThis() {
  1192. assert(CXXThisValue && "no 'this' value for this function");
  1193. return CXXThisValue;
  1194. }
  1195. /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
  1196. /// virtual bases.
  1197. llvm::Value *LoadCXXVTT() {
  1198. assert(CXXVTTValue && "no VTT value for this function");
  1199. return CXXVTTValue;
  1200. }
  1201. /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
  1202. /// complete class to the given direct base.
  1203. llvm::Value *
  1204. GetAddressOfDirectBaseInCompleteClass(llvm::Value *Value,
  1205. const CXXRecordDecl *Derived,
  1206. const CXXRecordDecl *Base,
  1207. bool BaseIsVirtual);
  1208. /// GetAddressOfBaseClass - This function will add the necessary delta to the
  1209. /// load of 'this' and returns address of the base class.
  1210. llvm::Value *GetAddressOfBaseClass(llvm::Value *Value,
  1211. const CXXRecordDecl *Derived,
  1212. CastExpr::path_const_iterator PathBegin,
  1213. CastExpr::path_const_iterator PathEnd,
  1214. bool NullCheckValue);
  1215. llvm::Value *GetAddressOfDerivedClass(llvm::Value *Value,
  1216. const CXXRecordDecl *Derived,
  1217. CastExpr::path_const_iterator PathBegin,
  1218. CastExpr::path_const_iterator PathEnd,
  1219. bool NullCheckValue);
  1220. llvm::Value *GetVirtualBaseClassOffset(llvm::Value *This,
  1221. const CXXRecordDecl *ClassDecl,
  1222. const CXXRecordDecl *BaseClassDecl);
  1223. void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1224. CXXCtorType CtorType,
  1225. const FunctionArgList &Args);
  1226. void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
  1227. bool ForVirtualBase, llvm::Value *This,
  1228. CallExpr::const_arg_iterator ArgBeg,
  1229. CallExpr::const_arg_iterator ArgEnd);
  1230. void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
  1231. llvm::Value *This, llvm::Value *Src,
  1232. CallExpr::const_arg_iterator ArgBeg,
  1233. CallExpr::const_arg_iterator ArgEnd);
  1234. void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
  1235. const ConstantArrayType *ArrayTy,
  1236. llvm::Value *ArrayPtr,
  1237. CallExpr::const_arg_iterator ArgBeg,
  1238. CallExpr::const_arg_iterator ArgEnd,
  1239. bool ZeroInitialization = false);
  1240. void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
  1241. llvm::Value *NumElements,
  1242. llvm::Value *ArrayPtr,
  1243. CallExpr::const_arg_iterator ArgBeg,
  1244. CallExpr::const_arg_iterator ArgEnd,
  1245. bool ZeroInitialization = false);
  1246. void EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
  1247. const ArrayType *Array,
  1248. llvm::Value *This);
  1249. void EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
  1250. llvm::Value *NumElements,
  1251. llvm::Value *This);
  1252. llvm::Function *GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D,
  1253. const ArrayType *Array,
  1254. llvm::Value *This);
  1255. void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
  1256. bool ForVirtualBase, llvm::Value *This);
  1257. void EmitNewArrayInitializer(const CXXNewExpr *E, llvm::Value *NewPtr,
  1258. llvm::Value *NumElements);
  1259. void EmitCXXTemporary(const CXXTemporary *Temporary, llvm::Value *Ptr);
  1260. llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
  1261. void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
  1262. void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
  1263. QualType DeleteTy);
  1264. llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E);
  1265. llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *DCE);
  1266. void EmitCheck(llvm::Value *, unsigned Size);
  1267. llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
  1268. bool isInc, bool isPre);
  1269. ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
  1270. bool isInc, bool isPre);
  1271. //===--------------------------------------------------------------------===//
  1272. // Declaration Emission
  1273. //===--------------------------------------------------------------------===//
  1274. /// EmitDecl - Emit a declaration.
  1275. ///
  1276. /// This function can be called with a null (unreachable) insert point.
  1277. void EmitDecl(const Decl &D);
  1278. /// EmitVarDecl - Emit a local variable declaration.
  1279. ///
  1280. /// This function can be called with a null (unreachable) insert point.
  1281. void EmitVarDecl(const VarDecl &D);
  1282. typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
  1283. llvm::Value *Address);
  1284. /// EmitAutoVarDecl - Emit an auto variable declaration.
  1285. ///
  1286. /// This function can be called with a null (unreachable) insert point.
  1287. void EmitAutoVarDecl(const VarDecl &D);
  1288. class AutoVarEmission {
  1289. friend class CodeGenFunction;
  1290. const VarDecl *Variable;
  1291. /// The alignment of the variable.
  1292. CharUnits Alignment;
  1293. /// The address of the alloca. Null if the variable was emitted
  1294. /// as a global constant.
  1295. llvm::Value *Address;
  1296. llvm::Value *NRVOFlag;
  1297. /// True if the variable is a __block variable.
  1298. bool IsByRef;
  1299. /// True if the variable is of aggregate type and has a constant
  1300. /// initializer.
  1301. bool IsConstantAggregate;
  1302. struct Invalid {};
  1303. AutoVarEmission(Invalid) : Variable(0) {}
  1304. AutoVarEmission(const VarDecl &variable)
  1305. : Variable(&variable), Address(0), NRVOFlag(0),
  1306. IsByRef(false), IsConstantAggregate(false) {}
  1307. bool wasEmittedAsGlobal() const { return Address == 0; }
  1308. public:
  1309. static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
  1310. /// Returns the address of the object within this declaration.
  1311. /// Note that this does not chase the forwarding pointer for
  1312. /// __block decls.
  1313. llvm::Value *getObjectAddress(CodeGenFunction &CGF) const {
  1314. if (!IsByRef) return Address;
  1315. return CGF.Builder.CreateStructGEP(Address,
  1316. CGF.getByRefValueLLVMField(Variable),
  1317. Variable->getNameAsString());
  1318. }
  1319. };
  1320. AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
  1321. void EmitAutoVarInit(const AutoVarEmission &emission);
  1322. void EmitAutoVarCleanups(const AutoVarEmission &emission);
  1323. void EmitStaticVarDecl(const VarDecl &D,
  1324. llvm::GlobalValue::LinkageTypes Linkage);
  1325. /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
  1326. void EmitParmDecl(const VarDecl &D, llvm::Value *Arg, unsigned ArgNo);
  1327. /// protectFromPeepholes - Protect a value that we're intending to
  1328. /// store to the side, but which will probably be used later, from
  1329. /// aggressive peepholing optimizations that might delete it.
  1330. ///
  1331. /// Pass the result to unprotectFromPeepholes to declare that
  1332. /// protection is no longer required.
  1333. ///
  1334. /// There's no particular reason why this shouldn't apply to
  1335. /// l-values, it's just that no existing peepholes work on pointers.
  1336. PeepholeProtection protectFromPeepholes(RValue rvalue);
  1337. void unprotectFromPeepholes(PeepholeProtection protection);
  1338. //===--------------------------------------------------------------------===//
  1339. // Statement Emission
  1340. //===--------------------------------------------------------------------===//
  1341. /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
  1342. void EmitStopPoint(const Stmt *S);
  1343. /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
  1344. /// this function even if there is no current insertion point.
  1345. ///
  1346. /// This function may clear the current insertion point; callers should use
  1347. /// EnsureInsertPoint if they wish to subsequently generate code without first
  1348. /// calling EmitBlock, EmitBranch, or EmitStmt.
  1349. void EmitStmt(const Stmt *S);
  1350. /// EmitSimpleStmt - Try to emit a "simple" statement which does not
  1351. /// necessarily require an insertion point or debug information; typically
  1352. /// because the statement amounts to a jump or a container of other
  1353. /// statements.
  1354. ///
  1355. /// \return True if the statement was handled.
  1356. bool EmitSimpleStmt(const Stmt *S);
  1357. RValue EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
  1358. AggValueSlot AVS = AggValueSlot::ignored());
  1359. /// EmitLabel - Emit the block for the given label. It is legal to call this
  1360. /// function even if there is no current insertion point.
  1361. void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
  1362. void EmitLabelStmt(const LabelStmt &S);
  1363. void EmitGotoStmt(const GotoStmt &S);
  1364. void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
  1365. void EmitIfStmt(const IfStmt &S);
  1366. void EmitWhileStmt(const WhileStmt &S);
  1367. void EmitDoStmt(const DoStmt &S);
  1368. void EmitForStmt(const ForStmt &S);
  1369. void EmitReturnStmt(const ReturnStmt &S);
  1370. void EmitDeclStmt(const DeclStmt &S);
  1371. void EmitBreakStmt(const BreakStmt &S);
  1372. void EmitContinueStmt(const ContinueStmt &S);
  1373. void EmitSwitchStmt(const SwitchStmt &S);
  1374. void EmitDefaultStmt(const DefaultStmt &S);
  1375. void EmitCaseStmt(const CaseStmt &S);
  1376. void EmitCaseStmtRange(const CaseStmt &S);
  1377. void EmitAsmStmt(const AsmStmt &S);
  1378. void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
  1379. void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
  1380. void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
  1381. void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
  1382. llvm::Constant *getUnwindResumeOrRethrowFn();
  1383. void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
  1384. void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
  1385. void EmitCXXTryStmt(const CXXTryStmt &S);
  1386. //===--------------------------------------------------------------------===//
  1387. // LValue Expression Emission
  1388. //===--------------------------------------------------------------------===//
  1389. /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
  1390. RValue GetUndefRValue(QualType Ty);
  1391. /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
  1392. /// and issue an ErrorUnsupported style diagnostic (using the
  1393. /// provided Name).
  1394. RValue EmitUnsupportedRValue(const Expr *E,
  1395. const char *Name);
  1396. /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
  1397. /// an ErrorUnsupported style diagnostic (using the provided Name).
  1398. LValue EmitUnsupportedLValue(const Expr *E,
  1399. const char *Name);
  1400. /// EmitLValue - Emit code to compute a designator that specifies the location
  1401. /// of the expression.
  1402. ///
  1403. /// This can return one of two things: a simple address or a bitfield
  1404. /// reference. In either case, the LLVM Value* in the LValue structure is
  1405. /// guaranteed to be an LLVM pointer type.
  1406. ///
  1407. /// If this returns a bitfield reference, nothing about the pointee type of
  1408. /// the LLVM value is known: For example, it may not be a pointer to an
  1409. /// integer.
  1410. ///
  1411. /// If this returns a normal address, and if the lvalue's C type is fixed
  1412. /// size, this method guarantees that the returned pointer type will point to
  1413. /// an LLVM type of the same size of the lvalue's type. If the lvalue has a
  1414. /// variable length type, this is not possible.
  1415. ///
  1416. LValue EmitLValue(const Expr *E);
  1417. /// EmitCheckedLValue - Same as EmitLValue but additionally we generate
  1418. /// checking code to guard against undefined behavior. This is only
  1419. /// suitable when we know that the address will be used to access the
  1420. /// object.
  1421. LValue EmitCheckedLValue(const Expr *E);
  1422. /// EmitToMemory - Change a scalar value from its value
  1423. /// representation to its in-memory representation.
  1424. llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
  1425. /// EmitFromMemory - Change a scalar value from its memory
  1426. /// representation to its value representation.
  1427. llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
  1428. /// EmitLoadOfScalar - Load a scalar value from an address, taking
  1429. /// care to appropriately convert from the memory representation to
  1430. /// the LLVM value representation.
  1431. llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
  1432. unsigned Alignment, QualType Ty,
  1433. llvm::MDNode *TBAAInfo = 0);
  1434. /// EmitStoreOfScalar - Store a scalar value to an address, taking
  1435. /// care to appropriately convert from the memory representation to
  1436. /// the LLVM value representation.
  1437. void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
  1438. bool Volatile, unsigned Alignment, QualType Ty,
  1439. llvm::MDNode *TBAAInfo = 0);
  1440. /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
  1441. /// this method emits the address of the lvalue, then loads the result as an
  1442. /// rvalue, returning the rvalue.
  1443. RValue EmitLoadOfLValue(LValue V, QualType LVType);
  1444. RValue EmitLoadOfExtVectorElementLValue(LValue V, QualType LVType);
  1445. RValue EmitLoadOfBitfieldLValue(LValue LV, QualType ExprType);
  1446. RValue EmitLoadOfPropertyRefLValue(LValue LV,
  1447. ReturnValueSlot Return = ReturnValueSlot());
  1448. /// EmitStoreThroughLValue - Store the specified rvalue into the specified
  1449. /// lvalue, where both are guaranteed to the have the same type, and that type
  1450. /// is 'Ty'.
  1451. void EmitStoreThroughLValue(RValue Src, LValue Dst, QualType Ty);
  1452. void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst,
  1453. QualType Ty);
  1454. void EmitStoreThroughPropertyRefLValue(RValue Src, LValue Dst);
  1455. /// EmitStoreThroughLValue - Store Src into Dst with same constraints as
  1456. /// EmitStoreThroughLValue.
  1457. ///
  1458. /// \param Result [out] - If non-null, this will be set to a Value* for the
  1459. /// bit-field contents after the store, appropriate for use as the result of
  1460. /// an assignment to the bit-field.
  1461. void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, QualType Ty,
  1462. llvm::Value **Result=0);
  1463. /// Emit an l-value for an assignment (simple or compound) of complex type.
  1464. LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
  1465. LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
  1466. // Note: only availabe for agg return types
  1467. LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
  1468. LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
  1469. // Note: only available for agg return types
  1470. LValue EmitCallExprLValue(const CallExpr *E);
  1471. // Note: only available for agg return types
  1472. LValue EmitVAArgExprLValue(const VAArgExpr *E);
  1473. LValue EmitDeclRefLValue(const DeclRefExpr *E);
  1474. LValue EmitStringLiteralLValue(const StringLiteral *E);
  1475. LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
  1476. LValue EmitPredefinedLValue(const PredefinedExpr *E);
  1477. LValue EmitUnaryOpLValue(const UnaryOperator *E);
  1478. LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E);
  1479. LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
  1480. LValue EmitMemberExpr(const MemberExpr *E);
  1481. LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
  1482. LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
  1483. LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E);
  1484. LValue EmitCastLValue(const CastExpr *E);
  1485. LValue EmitNullInitializationLValue(const CXXScalarValueInitExpr *E);
  1486. LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
  1487. llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
  1488. const ObjCIvarDecl *Ivar);
  1489. LValue EmitLValueForAnonRecordField(llvm::Value* Base,
  1490. const IndirectFieldDecl* Field,
  1491. unsigned CVRQualifiers);
  1492. LValue EmitLValueForField(llvm::Value* Base, const FieldDecl* Field,
  1493. unsigned CVRQualifiers);
  1494. /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
  1495. /// if the Field is a reference, this will return the address of the reference
  1496. /// and not the address of the value stored in the reference.
  1497. LValue EmitLValueForFieldInitialization(llvm::Value* Base,
  1498. const FieldDecl* Field,
  1499. unsigned CVRQualifiers);
  1500. LValue EmitLValueForIvar(QualType ObjectTy,
  1501. llvm::Value* Base, const ObjCIvarDecl *Ivar,
  1502. unsigned CVRQualifiers);
  1503. LValue EmitLValueForBitfield(llvm::Value* Base, const FieldDecl* Field,
  1504. unsigned CVRQualifiers);
  1505. LValue EmitBlockDeclRefLValue(const BlockDeclRefExpr *E);
  1506. LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
  1507. LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
  1508. LValue EmitExprWithCleanupsLValue(const ExprWithCleanups *E);
  1509. LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
  1510. LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
  1511. LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
  1512. LValue EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E);
  1513. LValue EmitStmtExprLValue(const StmtExpr *E);
  1514. LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
  1515. LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
  1516. void EmitDeclRefExprDbgValue(const DeclRefExpr *E, llvm::Constant *Init);
  1517. //===--------------------------------------------------------------------===//
  1518. // Scalar Expression Emission
  1519. //===--------------------------------------------------------------------===//
  1520. /// EmitCall - Generate a call of the given function, expecting the given
  1521. /// result type, and using the given argument list which specifies both the
  1522. /// LLVM arguments and the types they were derived from.
  1523. ///
  1524. /// \param TargetDecl - If given, the decl of the function in a direct call;
  1525. /// used to set attributes on the call (noreturn, etc.).
  1526. RValue EmitCall(const CGFunctionInfo &FnInfo,
  1527. llvm::Value *Callee,
  1528. ReturnValueSlot ReturnValue,
  1529. const CallArgList &Args,
  1530. const Decl *TargetDecl = 0,
  1531. llvm::Instruction **callOrInvoke = 0);
  1532. RValue EmitCall(QualType FnType, llvm::Value *Callee,
  1533. ReturnValueSlot ReturnValue,
  1534. CallExpr::const_arg_iterator ArgBeg,
  1535. CallExpr::const_arg_iterator ArgEnd,
  1536. const Decl *TargetDecl = 0);
  1537. RValue EmitCallExpr(const CallExpr *E,
  1538. ReturnValueSlot ReturnValue = ReturnValueSlot());
  1539. llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
  1540. llvm::Value * const *ArgBegin,
  1541. llvm::Value * const *ArgEnd,
  1542. const llvm::Twine &Name = "");
  1543. llvm::Value *BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
  1544. const llvm::Type *Ty);
  1545. llvm::Value *BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
  1546. llvm::Value *This, const llvm::Type *Ty);
  1547. llvm::Value *BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
  1548. NestedNameSpecifier *Qual,
  1549. const llvm::Type *Ty);
  1550. llvm::Value *BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD,
  1551. CXXDtorType Type,
  1552. const CXXRecordDecl *RD);
  1553. RValue EmitCXXMemberCall(const CXXMethodDecl *MD,
  1554. llvm::Value *Callee,
  1555. ReturnValueSlot ReturnValue,
  1556. llvm::Value *This,
  1557. llvm::Value *VTT,
  1558. CallExpr::const_arg_iterator ArgBeg,
  1559. CallExpr::const_arg_iterator ArgEnd);
  1560. RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
  1561. ReturnValueSlot ReturnValue);
  1562. RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
  1563. ReturnValueSlot ReturnValue);
  1564. RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
  1565. const CXXMethodDecl *MD,
  1566. ReturnValueSlot ReturnValue);
  1567. RValue EmitBuiltinExpr(const FunctionDecl *FD,
  1568. unsigned BuiltinID, const CallExpr *E);
  1569. RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
  1570. /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
  1571. /// is unhandled by the current target.
  1572. llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  1573. llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  1574. llvm::Value *EmitNeonCall(llvm::Function *F,
  1575. llvm::SmallVectorImpl<llvm::Value*> &O,
  1576. const char *name,
  1577. unsigned shift = 0, bool rightshift = false);
  1578. llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
  1579. llvm::Value *EmitNeonShiftVector(llvm::Value *V, const llvm::Type *Ty,
  1580. bool negateForRightShift);
  1581. llvm::Value *BuildVector(const llvm::SmallVectorImpl<llvm::Value*> &Ops);
  1582. llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  1583. llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  1584. llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
  1585. llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
  1586. llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
  1587. RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
  1588. ReturnValueSlot Return = ReturnValueSlot());
  1589. /// EmitReferenceBindingToExpr - Emits a reference binding to the passed in
  1590. /// expression. Will emit a temporary variable if E is not an LValue.
  1591. RValue EmitReferenceBindingToExpr(const Expr* E,
  1592. const NamedDecl *InitializedDecl);
  1593. //===--------------------------------------------------------------------===//
  1594. // Expression Emission
  1595. //===--------------------------------------------------------------------===//
  1596. // Expressions are broken into three classes: scalar, complex, aggregate.
  1597. /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
  1598. /// scalar type, returning the result.
  1599. llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
  1600. /// EmitScalarConversion - Emit a conversion from the specified type to the
  1601. /// specified destination type, both of which are LLVM scalar types.
  1602. llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
  1603. QualType DstTy);
  1604. /// EmitComplexToScalarConversion - Emit a conversion from the specified
  1605. /// complex type to the specified destination type, where the destination type
  1606. /// is an LLVM scalar type.
  1607. llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
  1608. QualType DstTy);
  1609. /// EmitAggExpr - Emit the computation of the specified expression
  1610. /// of aggregate type. The result is computed into the given slot,
  1611. /// which may be null to indicate that the value is not needed.
  1612. void EmitAggExpr(const Expr *E, AggValueSlot AS, bool IgnoreResult = false);
  1613. /// EmitAggExprToLValue - Emit the computation of the specified expression of
  1614. /// aggregate type into a temporary LValue.
  1615. LValue EmitAggExprToLValue(const Expr *E);
  1616. /// EmitGCMemmoveCollectable - Emit special API for structs with object
  1617. /// pointers.
  1618. void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr,
  1619. QualType Ty);
  1620. /// EmitComplexExpr - Emit the computation of the specified expression of
  1621. /// complex type, returning the result.
  1622. ComplexPairTy EmitComplexExpr(const Expr *E,
  1623. bool IgnoreReal = false,
  1624. bool IgnoreImag = false);
  1625. /// EmitComplexExprIntoAddr - Emit the computation of the specified expression
  1626. /// of complex type, storing into the specified Value*.
  1627. void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr,
  1628. bool DestIsVolatile);
  1629. /// StoreComplexToAddr - Store a complex number into the specified address.
  1630. void StoreComplexToAddr(ComplexPairTy V, llvm::Value *DestAddr,
  1631. bool DestIsVolatile);
  1632. /// LoadComplexFromAddr - Load a complex number from the specified address.
  1633. ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile);
  1634. /// CreateStaticVarDecl - Create a zero-initialized LLVM global for
  1635. /// a static local variable.
  1636. llvm::GlobalVariable *CreateStaticVarDecl(const VarDecl &D,
  1637. const char *Separator,
  1638. llvm::GlobalValue::LinkageTypes Linkage);
  1639. /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
  1640. /// global variable that has already been created for it. If the initializer
  1641. /// has a different type than GV does, this may free GV and return a different
  1642. /// one. Otherwise it just returns GV.
  1643. llvm::GlobalVariable *
  1644. AddInitializerToStaticVarDecl(const VarDecl &D,
  1645. llvm::GlobalVariable *GV);
  1646. /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
  1647. /// variable with global storage.
  1648. void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr);
  1649. /// EmitCXXGlobalDtorRegistration - Emits a call to register the global ptr
  1650. /// with the C++ runtime so that its destructor will be called at exit.
  1651. void EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn,
  1652. llvm::Constant *DeclPtr);
  1653. /// Emit code in this function to perform a guarded variable
  1654. /// initialization. Guarded initializations are used when it's not
  1655. /// possible to prove that an initialization will be done exactly
  1656. /// once, e.g. with a static local variable or a static data member
  1657. /// of a class template.
  1658. void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr);
  1659. /// GenerateCXXGlobalInitFunc - Generates code for initializing global
  1660. /// variables.
  1661. void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
  1662. llvm::Constant **Decls,
  1663. unsigned NumDecls);
  1664. /// GenerateCXXGlobalDtorFunc - Generates code for destroying global
  1665. /// variables.
  1666. void GenerateCXXGlobalDtorFunc(llvm::Function *Fn,
  1667. const std::vector<std::pair<llvm::WeakVH,
  1668. llvm::Constant*> > &DtorsAndObjects);
  1669. void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
  1670. const VarDecl *D,
  1671. llvm::GlobalVariable *Addr);
  1672. void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
  1673. void EmitSynthesizedCXXCopyCtor(llvm::Value *Dest, llvm::Value *Src,
  1674. const Expr *Exp);
  1675. RValue EmitExprWithCleanups(const ExprWithCleanups *E,
  1676. AggValueSlot Slot =AggValueSlot::ignored());
  1677. void EmitCXXThrowExpr(const CXXThrowExpr *E);
  1678. //===--------------------------------------------------------------------===//
  1679. // Internal Helpers
  1680. //===--------------------------------------------------------------------===//
  1681. /// ContainsLabel - Return true if the statement contains a label in it. If
  1682. /// this statement is not executed normally, it not containing a label means
  1683. /// that we can just remove the code.
  1684. static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
  1685. /// containsBreak - Return true if the statement contains a break out of it.
  1686. /// If the statement (recursively) contains a switch or loop with a break
  1687. /// inside of it, this is fine.
  1688. static bool containsBreak(const Stmt *S);
  1689. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  1690. /// to a constant, or if it does but contains a label, return false. If it
  1691. /// constant folds return true and set the boolean result in Result.
  1692. bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result);
  1693. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  1694. /// to a constant, or if it does but contains a label, return false. If it
  1695. /// constant folds return true and set the folded value.
  1696. bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APInt &Result);
  1697. /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
  1698. /// if statement) to the specified blocks. Based on the condition, this might
  1699. /// try to simplify the codegen of the conditional based on the branch.
  1700. void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
  1701. llvm::BasicBlock *FalseBlock);
  1702. /// getTrapBB - Create a basic block that will call the trap intrinsic. We'll
  1703. /// generate a branch around the created basic block as necessary.
  1704. llvm::BasicBlock *getTrapBB();
  1705. /// EmitCallArg - Emit a single call argument.
  1706. RValue EmitCallArg(const Expr *E, QualType ArgType);
  1707. /// EmitDelegateCallArg - We are performing a delegate call; that
  1708. /// is, the current function is delegating to another one. Produce
  1709. /// a r-value suitable for passing the given parameter.
  1710. RValue EmitDelegateCallArg(const VarDecl *Param);
  1711. private:
  1712. void EmitReturnOfRValue(RValue RV, QualType Ty);
  1713. /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
  1714. /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
  1715. ///
  1716. /// \param AI - The first function argument of the expansion.
  1717. /// \return The argument following the last expanded function
  1718. /// argument.
  1719. llvm::Function::arg_iterator
  1720. ExpandTypeFromArgs(QualType Ty, LValue Dst,
  1721. llvm::Function::arg_iterator AI);
  1722. /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg
  1723. /// Ty, into individual arguments on the provided vector \arg Args. See
  1724. /// ABIArgInfo::Expand.
  1725. void ExpandTypeToArgs(QualType Ty, RValue Src,
  1726. llvm::SmallVector<llvm::Value*, 16> &Args);
  1727. llvm::Value* EmitAsmInput(const AsmStmt &S,
  1728. const TargetInfo::ConstraintInfo &Info,
  1729. const Expr *InputExpr, std::string &ConstraintStr);
  1730. llvm::Value* EmitAsmInputLValue(const AsmStmt &S,
  1731. const TargetInfo::ConstraintInfo &Info,
  1732. LValue InputValue, QualType InputType,
  1733. std::string &ConstraintStr);
  1734. /// EmitCallArgs - Emit call arguments for a function.
  1735. /// The CallArgTypeInfo parameter is used for iterating over the known
  1736. /// argument types of the function being called.
  1737. template<typename T>
  1738. void EmitCallArgs(CallArgList& Args, const T* CallArgTypeInfo,
  1739. CallExpr::const_arg_iterator ArgBeg,
  1740. CallExpr::const_arg_iterator ArgEnd) {
  1741. CallExpr::const_arg_iterator Arg = ArgBeg;
  1742. // First, use the argument types that the type info knows about
  1743. if (CallArgTypeInfo) {
  1744. for (typename T::arg_type_iterator I = CallArgTypeInfo->arg_type_begin(),
  1745. E = CallArgTypeInfo->arg_type_end(); I != E; ++I, ++Arg) {
  1746. assert(Arg != ArgEnd && "Running over edge of argument list!");
  1747. QualType ArgType = *I;
  1748. #ifndef NDEBUG
  1749. QualType ActualArgType = Arg->getType();
  1750. if (ArgType->isPointerType() && ActualArgType->isPointerType()) {
  1751. QualType ActualBaseType =
  1752. ActualArgType->getAs<PointerType>()->getPointeeType();
  1753. QualType ArgBaseType =
  1754. ArgType->getAs<PointerType>()->getPointeeType();
  1755. if (ArgBaseType->isVariableArrayType()) {
  1756. if (const VariableArrayType *VAT =
  1757. getContext().getAsVariableArrayType(ActualBaseType)) {
  1758. if (!VAT->getSizeExpr())
  1759. ActualArgType = ArgType;
  1760. }
  1761. }
  1762. }
  1763. assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
  1764. getTypePtr() ==
  1765. getContext().getCanonicalType(ActualArgType).getTypePtr() &&
  1766. "type mismatch in call argument!");
  1767. #endif
  1768. Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
  1769. ArgType));
  1770. }
  1771. // Either we've emitted all the call args, or we have a call to a
  1772. // variadic function.
  1773. assert((Arg == ArgEnd || CallArgTypeInfo->isVariadic()) &&
  1774. "Extra arguments in non-variadic function!");
  1775. }
  1776. // If we still have any arguments, emit them using the type of the argument.
  1777. for (; Arg != ArgEnd; ++Arg) {
  1778. QualType ArgType = Arg->getType();
  1779. Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
  1780. ArgType));
  1781. }
  1782. }
  1783. const TargetCodeGenInfo &getTargetHooks() const {
  1784. return CGM.getTargetCodeGenInfo();
  1785. }
  1786. void EmitDeclMetadata();
  1787. };
  1788. /// Helper class with most of the code for saving a value for a
  1789. /// conditional expression cleanup.
  1790. struct DominatingLLVMValue {
  1791. typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
  1792. /// Answer whether the given value needs extra work to be saved.
  1793. static bool needsSaving(llvm::Value *value) {
  1794. // If it's not an instruction, we don't need to save.
  1795. if (!isa<llvm::Instruction>(value)) return false;
  1796. // If it's an instruction in the entry block, we don't need to save.
  1797. llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
  1798. return (block != &block->getParent()->getEntryBlock());
  1799. }
  1800. /// Try to save the given value.
  1801. static saved_type save(CodeGenFunction &CGF, llvm::Value *value) {
  1802. if (!needsSaving(value)) return saved_type(value, false);
  1803. // Otherwise we need an alloca.
  1804. llvm::Value *alloca =
  1805. CGF.CreateTempAlloca(value->getType(), "cond-cleanup.save");
  1806. CGF.Builder.CreateStore(value, alloca);
  1807. return saved_type(alloca, true);
  1808. }
  1809. static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) {
  1810. if (!value.getInt()) return value.getPointer();
  1811. return CGF.Builder.CreateLoad(value.getPointer());
  1812. }
  1813. };
  1814. /// A partial specialization of DominatingValue for llvm::Values that
  1815. /// might be llvm::Instructions.
  1816. template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
  1817. typedef T *type;
  1818. static type restore(CodeGenFunction &CGF, saved_type value) {
  1819. return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
  1820. }
  1821. };
  1822. /// A specialization of DominatingValue for RValue.
  1823. template <> struct DominatingValue<RValue> {
  1824. typedef RValue type;
  1825. class saved_type {
  1826. enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
  1827. AggregateAddress, ComplexAddress };
  1828. llvm::Value *Value;
  1829. Kind K;
  1830. saved_type(llvm::Value *v, Kind k) : Value(v), K(k) {}
  1831. public:
  1832. static bool needsSaving(RValue value);
  1833. static saved_type save(CodeGenFunction &CGF, RValue value);
  1834. RValue restore(CodeGenFunction &CGF);
  1835. // implementations in CGExprCXX.cpp
  1836. };
  1837. static bool needsSaving(type value) {
  1838. return saved_type::needsSaving(value);
  1839. }
  1840. static saved_type save(CodeGenFunction &CGF, type value) {
  1841. return saved_type::save(CGF, value);
  1842. }
  1843. static type restore(CodeGenFunction &CGF, saved_type value) {
  1844. return value.restore(CGF);
  1845. }
  1846. };
  1847. } // end namespace CodeGen
  1848. } // end namespace clang
  1849. #endif