MC: Clean up MCExpr naming. NFC.
[oota-llvm.git] / lib / MC / MCExpr.cpp
1 //===- MCExpr.cpp - Assembly Level Expression Implementation --------------===//
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 #include "llvm/MC/MCExpr.h"
11 #include "llvm/ADT/Statistic.h"
12 #include "llvm/ADT/StringSwitch.h"
13 #include "llvm/MC/MCAsmInfo.h"
14 #include "llvm/MC/MCAsmLayout.h"
15 #include "llvm/MC/MCAssembler.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCObjectWriter.h"
18 #include "llvm/MC/MCSymbol.h"
19 #include "llvm/MC/MCValue.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/raw_ostream.h"
23 using namespace llvm;
24
25 #define DEBUG_TYPE "mcexpr"
26
27 namespace {
28 namespace stats {
29 STATISTIC(MCExprEvaluate, "Number of MCExpr evaluations");
30 }
31 }
32
33 void MCExpr::print(raw_ostream &OS) const {
34   switch (getKind()) {
35   case MCExpr::Target:
36     return cast<MCTargetExpr>(this)->printImpl(OS);
37   case MCExpr::Constant:
38     OS << cast<MCConstantExpr>(*this).getValue();
39     return;
40
41   case MCExpr::SymbolRef: {
42     const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(*this);
43     const MCSymbol &Sym = SRE.getSymbol();
44     // Parenthesize names that start with $ so that they don't look like
45     // absolute names.
46     bool UseParens = !Sym.getName().empty() && Sym.getName()[0] == '$';
47     if (UseParens)
48       OS << '(' << Sym << ')';
49     else
50       OS << Sym;
51
52     if (SRE.getKind() != MCSymbolRefExpr::VK_None)
53       SRE.printVariantKind(OS);
54
55     return;
56   }
57
58   case MCExpr::Unary: {
59     const MCUnaryExpr &UE = cast<MCUnaryExpr>(*this);
60     switch (UE.getOpcode()) {
61     case MCUnaryExpr::LNot:  OS << '!'; break;
62     case MCUnaryExpr::Minus: OS << '-'; break;
63     case MCUnaryExpr::Not:   OS << '~'; break;
64     case MCUnaryExpr::Plus:  OS << '+'; break;
65     }
66     OS << *UE.getSubExpr();
67     return;
68   }
69
70   case MCExpr::Binary: {
71     const MCBinaryExpr &BE = cast<MCBinaryExpr>(*this);
72
73     // Only print parens around the LHS if it is non-trivial.
74     if (isa<MCConstantExpr>(BE.getLHS()) || isa<MCSymbolRefExpr>(BE.getLHS())) {
75       OS << *BE.getLHS();
76     } else {
77       OS << '(' << *BE.getLHS() << ')';
78     }
79
80     switch (BE.getOpcode()) {
81     case MCBinaryExpr::Add:
82       // Print "X-42" instead of "X+-42".
83       if (const MCConstantExpr *RHSC = dyn_cast<MCConstantExpr>(BE.getRHS())) {
84         if (RHSC->getValue() < 0) {
85           OS << RHSC->getValue();
86           return;
87         }
88       }
89
90       OS <<  '+';
91       break;
92     case MCBinaryExpr::AShr: OS << ">>"; break;
93     case MCBinaryExpr::And:  OS <<  '&'; break;
94     case MCBinaryExpr::Div:  OS <<  '/'; break;
95     case MCBinaryExpr::EQ:   OS << "=="; break;
96     case MCBinaryExpr::GT:   OS <<  '>'; break;
97     case MCBinaryExpr::GTE:  OS << ">="; break;
98     case MCBinaryExpr::LAnd: OS << "&&"; break;
99     case MCBinaryExpr::LOr:  OS << "||"; break;
100     case MCBinaryExpr::LShr: OS << ">>"; break;
101     case MCBinaryExpr::LT:   OS <<  '<'; break;
102     case MCBinaryExpr::LTE:  OS << "<="; break;
103     case MCBinaryExpr::Mod:  OS <<  '%'; break;
104     case MCBinaryExpr::Mul:  OS <<  '*'; break;
105     case MCBinaryExpr::NE:   OS << "!="; break;
106     case MCBinaryExpr::Or:   OS <<  '|'; break;
107     case MCBinaryExpr::Shl:  OS << "<<"; break;
108     case MCBinaryExpr::Sub:  OS <<  '-'; break;
109     case MCBinaryExpr::Xor:  OS <<  '^'; break;
110     }
111
112     // Only print parens around the LHS if it is non-trivial.
113     if (isa<MCConstantExpr>(BE.getRHS()) || isa<MCSymbolRefExpr>(BE.getRHS())) {
114       OS << *BE.getRHS();
115     } else {
116       OS << '(' << *BE.getRHS() << ')';
117     }
118     return;
119   }
120   }
121
122   llvm_unreachable("Invalid expression kind!");
123 }
124
125 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
126 void MCExpr::dump() const {
127   dbgs() << *this;
128   dbgs() << '\n';
129 }
130 #endif
131
132 /* *** */
133
134 const MCBinaryExpr *MCBinaryExpr::create(Opcode Opc, const MCExpr *LHS,
135                                          const MCExpr *RHS, MCContext &Ctx) {
136   return new (Ctx) MCBinaryExpr(Opc, LHS, RHS);
137 }
138
139 const MCUnaryExpr *MCUnaryExpr::create(Opcode Opc, const MCExpr *Expr,
140                                        MCContext &Ctx) {
141   return new (Ctx) MCUnaryExpr(Opc, Expr);
142 }
143
144 const MCConstantExpr *MCConstantExpr::create(int64_t Value, MCContext &Ctx) {
145   return new (Ctx) MCConstantExpr(Value);
146 }
147
148 /* *** */
149
150 MCSymbolRefExpr::MCSymbolRefExpr(const MCSymbol *Symbol, VariantKind Kind,
151                                  const MCAsmInfo *MAI)
152     : MCExpr(MCExpr::SymbolRef), Kind(Kind),
153       UseParensForSymbolVariant(MAI->useParensForSymbolVariant()),
154       HasSubsectionsViaSymbols(MAI->hasSubsectionsViaSymbols()),
155       Symbol(Symbol) {
156   assert(Symbol);
157 }
158
159 const MCSymbolRefExpr *MCSymbolRefExpr::create(const MCSymbol *Sym,
160                                                VariantKind Kind,
161                                                MCContext &Ctx) {
162   return new (Ctx) MCSymbolRefExpr(Sym, Kind, Ctx.getAsmInfo());
163 }
164
165 const MCSymbolRefExpr *MCSymbolRefExpr::create(StringRef Name, VariantKind Kind,
166                                                MCContext &Ctx) {
167   return create(Ctx.getOrCreateSymbol(Name), Kind, Ctx);
168 }
169
170 StringRef MCSymbolRefExpr::getVariantKindName(VariantKind Kind) {
171   switch (Kind) {
172   case VK_Invalid: return "<<invalid>>";
173   case VK_None: return "<<none>>";
174
175   case VK_GOT: return "GOT";
176   case VK_GOTOFF: return "GOTOFF";
177   case VK_GOTPCREL: return "GOTPCREL";
178   case VK_GOTTPOFF: return "GOTTPOFF";
179   case VK_INDNTPOFF: return "INDNTPOFF";
180   case VK_NTPOFF: return "NTPOFF";
181   case VK_GOTNTPOFF: return "GOTNTPOFF";
182   case VK_PLT: return "PLT";
183   case VK_TLSGD: return "TLSGD";
184   case VK_TLSLD: return "TLSLD";
185   case VK_TLSLDM: return "TLSLDM";
186   case VK_TPOFF: return "TPOFF";
187   case VK_DTPOFF: return "DTPOFF";
188   case VK_TLVP: return "TLVP";
189   case VK_TLVPPAGE: return "TLVPPAGE";
190   case VK_TLVPPAGEOFF: return "TLVPPAGEOFF";
191   case VK_PAGE: return "PAGE";
192   case VK_PAGEOFF: return "PAGEOFF";
193   case VK_GOTPAGE: return "GOTPAGE";
194   case VK_GOTPAGEOFF: return "GOTPAGEOFF";
195   case VK_SECREL: return "SECREL32";
196   case VK_SIZE: return "SIZE";
197   case VK_WEAKREF: return "WEAKREF";
198   case VK_ARM_NONE: return "none";
199   case VK_ARM_TARGET1: return "target1";
200   case VK_ARM_TARGET2: return "target2";
201   case VK_ARM_PREL31: return "prel31";
202   case VK_ARM_SBREL: return "sbrel";
203   case VK_ARM_TLSLDO: return "tlsldo";
204   case VK_ARM_TLSCALL: return "tlscall";
205   case VK_ARM_TLSDESC: return "tlsdesc";
206   case VK_ARM_TLSDESCSEQ: return "tlsdescseq";
207   case VK_PPC_LO: return "l";
208   case VK_PPC_HI: return "h";
209   case VK_PPC_HA: return "ha";
210   case VK_PPC_HIGHER: return "higher";
211   case VK_PPC_HIGHERA: return "highera";
212   case VK_PPC_HIGHEST: return "highest";
213   case VK_PPC_HIGHESTA: return "highesta";
214   case VK_PPC_GOT_LO: return "got@l";
215   case VK_PPC_GOT_HI: return "got@h";
216   case VK_PPC_GOT_HA: return "got@ha";
217   case VK_PPC_TOCBASE: return "tocbase";
218   case VK_PPC_TOC: return "toc";
219   case VK_PPC_TOC_LO: return "toc@l";
220   case VK_PPC_TOC_HI: return "toc@h";
221   case VK_PPC_TOC_HA: return "toc@ha";
222   case VK_PPC_DTPMOD: return "dtpmod";
223   case VK_PPC_TPREL: return "tprel";
224   case VK_PPC_TPREL_LO: return "tprel@l";
225   case VK_PPC_TPREL_HI: return "tprel@h";
226   case VK_PPC_TPREL_HA: return "tprel@ha";
227   case VK_PPC_TPREL_HIGHER: return "tprel@higher";
228   case VK_PPC_TPREL_HIGHERA: return "tprel@highera";
229   case VK_PPC_TPREL_HIGHEST: return "tprel@highest";
230   case VK_PPC_TPREL_HIGHESTA: return "tprel@highesta";
231   case VK_PPC_DTPREL: return "dtprel";
232   case VK_PPC_DTPREL_LO: return "dtprel@l";
233   case VK_PPC_DTPREL_HI: return "dtprel@h";
234   case VK_PPC_DTPREL_HA: return "dtprel@ha";
235   case VK_PPC_DTPREL_HIGHER: return "dtprel@higher";
236   case VK_PPC_DTPREL_HIGHERA: return "dtprel@highera";
237   case VK_PPC_DTPREL_HIGHEST: return "dtprel@highest";
238   case VK_PPC_DTPREL_HIGHESTA: return "dtprel@highesta";
239   case VK_PPC_GOT_TPREL: return "got@tprel";
240   case VK_PPC_GOT_TPREL_LO: return "got@tprel@l";
241   case VK_PPC_GOT_TPREL_HI: return "got@tprel@h";
242   case VK_PPC_GOT_TPREL_HA: return "got@tprel@ha";
243   case VK_PPC_GOT_DTPREL: return "got@dtprel";
244   case VK_PPC_GOT_DTPREL_LO: return "got@dtprel@l";
245   case VK_PPC_GOT_DTPREL_HI: return "got@dtprel@h";
246   case VK_PPC_GOT_DTPREL_HA: return "got@dtprel@ha";
247   case VK_PPC_TLS: return "tls";
248   case VK_PPC_GOT_TLSGD: return "got@tlsgd";
249   case VK_PPC_GOT_TLSGD_LO: return "got@tlsgd@l";
250   case VK_PPC_GOT_TLSGD_HI: return "got@tlsgd@h";
251   case VK_PPC_GOT_TLSGD_HA: return "got@tlsgd@ha";
252   case VK_PPC_TLSGD: return "tlsgd";
253   case VK_PPC_GOT_TLSLD: return "got@tlsld";
254   case VK_PPC_GOT_TLSLD_LO: return "got@tlsld@l";
255   case VK_PPC_GOT_TLSLD_HI: return "got@tlsld@h";
256   case VK_PPC_GOT_TLSLD_HA: return "got@tlsld@ha";
257   case VK_PPC_TLSLD: return "tlsld";
258   case VK_PPC_LOCAL: return "local";
259   case VK_Mips_GPREL: return "GPREL";
260   case VK_Mips_GOT_CALL: return "GOT_CALL";
261   case VK_Mips_GOT16: return "GOT16";
262   case VK_Mips_GOT: return "GOT";
263   case VK_Mips_ABS_HI: return "ABS_HI";
264   case VK_Mips_ABS_LO: return "ABS_LO";
265   case VK_Mips_TLSGD: return "TLSGD";
266   case VK_Mips_TLSLDM: return "TLSLDM";
267   case VK_Mips_DTPREL_HI: return "DTPREL_HI";
268   case VK_Mips_DTPREL_LO: return "DTPREL_LO";
269   case VK_Mips_GOTTPREL: return "GOTTPREL";
270   case VK_Mips_TPREL_HI: return "TPREL_HI";
271   case VK_Mips_TPREL_LO: return "TPREL_LO";
272   case VK_Mips_GPOFF_HI: return "GPOFF_HI";
273   case VK_Mips_GPOFF_LO: return "GPOFF_LO";
274   case VK_Mips_GOT_DISP: return "GOT_DISP";
275   case VK_Mips_GOT_PAGE: return "GOT_PAGE";
276   case VK_Mips_GOT_OFST: return "GOT_OFST";
277   case VK_Mips_HIGHER:   return "HIGHER";
278   case VK_Mips_HIGHEST:  return "HIGHEST";
279   case VK_Mips_GOT_HI16: return "GOT_HI16";
280   case VK_Mips_GOT_LO16: return "GOT_LO16";
281   case VK_Mips_CALL_HI16: return "CALL_HI16";
282   case VK_Mips_CALL_LO16: return "CALL_LO16";
283   case VK_Mips_PCREL_HI16: return "PCREL_HI16";
284   case VK_Mips_PCREL_LO16: return "PCREL_LO16";
285   case VK_COFF_IMGREL32: return "IMGREL";
286   case VK_Hexagon_PCREL: return "PCREL";
287   case VK_Hexagon_LO16: return "LO16";
288   case VK_Hexagon_HI16: return "HI16";
289   case VK_Hexagon_GPREL: return "GPREL";
290   case VK_Hexagon_GD_GOT: return "GDGOT";
291   case VK_Hexagon_LD_GOT: return "LDGOT";
292   case VK_Hexagon_GD_PLT: return "GDPLT";
293   case VK_Hexagon_LD_PLT: return "LDPLT";
294   case VK_Hexagon_IE: return "IE";
295   case VK_Hexagon_IE_GOT: return "IEGOT";
296   case VK_TPREL: return "tprel";
297   case VK_DTPREL: return "dtprel";
298   }
299   llvm_unreachable("Invalid variant kind");
300 }
301
302 MCSymbolRefExpr::VariantKind
303 MCSymbolRefExpr::getVariantKindForName(StringRef Name) {
304   return StringSwitch<VariantKind>(Name.lower())
305     .Case("got", VK_GOT)
306     .Case("gotoff", VK_GOTOFF)
307     .Case("gotpcrel", VK_GOTPCREL)
308     .Case("got_prel", VK_GOTPCREL)
309     .Case("gottpoff", VK_GOTTPOFF)
310     .Case("indntpoff", VK_INDNTPOFF)
311     .Case("ntpoff", VK_NTPOFF)
312     .Case("gotntpoff", VK_GOTNTPOFF)
313     .Case("plt", VK_PLT)
314     .Case("tlsgd", VK_TLSGD)
315     .Case("tlsld", VK_TLSLD)
316     .Case("tlsldm", VK_TLSLDM)
317     .Case("tpoff", VK_TPOFF)
318     .Case("dtpoff", VK_DTPOFF)
319     .Case("tlvp", VK_TLVP)
320     .Case("tlvppage", VK_TLVPPAGE)
321     .Case("tlvppageoff", VK_TLVPPAGEOFF)
322     .Case("page", VK_PAGE)
323     .Case("pageoff", VK_PAGEOFF)
324     .Case("gotpage", VK_GOTPAGE)
325     .Case("gotpageoff", VK_GOTPAGEOFF)
326     .Case("imgrel", VK_COFF_IMGREL32)
327     .Case("secrel32", VK_SECREL)
328     .Case("size", VK_SIZE)
329     .Case("l", VK_PPC_LO)
330     .Case("h", VK_PPC_HI)
331     .Case("ha", VK_PPC_HA)
332     .Case("higher", VK_PPC_HIGHER)
333     .Case("highera", VK_PPC_HIGHERA)
334     .Case("highest", VK_PPC_HIGHEST)
335     .Case("highesta", VK_PPC_HIGHESTA)
336     .Case("got@l", VK_PPC_GOT_LO)
337     .Case("got@h", VK_PPC_GOT_HI)
338     .Case("got@ha", VK_PPC_GOT_HA)
339     .Case("local", VK_PPC_LOCAL)
340     .Case("tocbase", VK_PPC_TOCBASE)
341     .Case("toc", VK_PPC_TOC)
342     .Case("toc@l", VK_PPC_TOC_LO)
343     .Case("toc@h", VK_PPC_TOC_HI)
344     .Case("toc@ha", VK_PPC_TOC_HA)
345     .Case("tls", VK_PPC_TLS)
346     .Case("dtpmod", VK_PPC_DTPMOD)
347     .Case("tprel", VK_PPC_TPREL)
348     .Case("tprel@l", VK_PPC_TPREL_LO)
349     .Case("tprel@h", VK_PPC_TPREL_HI)
350     .Case("tprel@ha", VK_PPC_TPREL_HA)
351     .Case("tprel@higher", VK_PPC_TPREL_HIGHER)
352     .Case("tprel@highera", VK_PPC_TPREL_HIGHERA)
353     .Case("tprel@highest", VK_PPC_TPREL_HIGHEST)
354     .Case("tprel@highesta", VK_PPC_TPREL_HIGHESTA)
355     .Case("dtprel", VK_PPC_DTPREL)
356     .Case("dtprel@l", VK_PPC_DTPREL_LO)
357     .Case("dtprel@h", VK_PPC_DTPREL_HI)
358     .Case("dtprel@ha", VK_PPC_DTPREL_HA)
359     .Case("dtprel@higher", VK_PPC_DTPREL_HIGHER)
360     .Case("dtprel@highera", VK_PPC_DTPREL_HIGHERA)
361     .Case("dtprel@highest", VK_PPC_DTPREL_HIGHEST)
362     .Case("dtprel@highesta", VK_PPC_DTPREL_HIGHESTA)
363     .Case("got@tprel", VK_PPC_GOT_TPREL)
364     .Case("got@tprel@l", VK_PPC_GOT_TPREL_LO)
365     .Case("got@tprel@h", VK_PPC_GOT_TPREL_HI)
366     .Case("got@tprel@ha", VK_PPC_GOT_TPREL_HA)
367     .Case("got@dtprel", VK_PPC_GOT_DTPREL)
368     .Case("got@dtprel@l", VK_PPC_GOT_DTPREL_LO)
369     .Case("got@dtprel@h", VK_PPC_GOT_DTPREL_HI)
370     .Case("got@dtprel@ha", VK_PPC_GOT_DTPREL_HA)
371     .Case("got@tlsgd", VK_PPC_GOT_TLSGD)
372     .Case("got@tlsgd@l", VK_PPC_GOT_TLSGD_LO)
373     .Case("got@tlsgd@h", VK_PPC_GOT_TLSGD_HI)
374     .Case("got@tlsgd@ha", VK_PPC_GOT_TLSGD_HA)
375     .Case("got@tlsld", VK_PPC_GOT_TLSLD)
376     .Case("got@tlsld@l", VK_PPC_GOT_TLSLD_LO)
377     .Case("got@tlsld@h", VK_PPC_GOT_TLSLD_HI)
378     .Case("got@tlsld@ha", VK_PPC_GOT_TLSLD_HA)
379     .Case("none", VK_ARM_NONE)
380     .Case("target1", VK_ARM_TARGET1)
381     .Case("target2", VK_ARM_TARGET2)
382     .Case("prel31", VK_ARM_PREL31)
383     .Case("sbrel", VK_ARM_SBREL)
384     .Case("tlsldo", VK_ARM_TLSLDO)
385     .Case("tlscall", VK_ARM_TLSCALL)
386     .Case("tlsdesc", VK_ARM_TLSDESC)
387     .Default(VK_Invalid);
388 }
389
390 void MCSymbolRefExpr::printVariantKind(raw_ostream &OS) const {
391   if (UseParensForSymbolVariant)
392     OS << '(' << MCSymbolRefExpr::getVariantKindName(getKind()) << ')';
393   else
394     OS << '@' << MCSymbolRefExpr::getVariantKindName(getKind());
395 }
396
397 /* *** */
398
399 void MCTargetExpr::anchor() {}
400
401 /* *** */
402
403 bool MCExpr::evaluateAsAbsolute(int64_t &Res) const {
404   return evaluateAsAbsolute(Res, nullptr, nullptr, nullptr);
405 }
406
407 bool MCExpr::evaluateAsAbsolute(int64_t &Res,
408                                 const MCAsmLayout &Layout) const {
409   return evaluateAsAbsolute(Res, &Layout.getAssembler(), &Layout, nullptr);
410 }
411
412 bool MCExpr::evaluateAsAbsolute(int64_t &Res,
413                                 const MCAsmLayout &Layout,
414                                 const SectionAddrMap &Addrs) const {
415   return evaluateAsAbsolute(Res, &Layout.getAssembler(), &Layout, &Addrs);
416 }
417
418 bool MCExpr::evaluateAsAbsolute(int64_t &Res, const MCAssembler &Asm) const {
419   return evaluateAsAbsolute(Res, &Asm, nullptr, nullptr);
420 }
421
422 bool MCExpr::evaluateKnownAbsolute(int64_t &Res,
423                                    const MCAsmLayout &Layout) const {
424   return evaluateAsAbsolute(Res, &Layout.getAssembler(), &Layout, nullptr,
425                             true);
426 }
427
428 bool MCExpr::evaluateAsAbsolute(int64_t &Res, const MCAssembler *Asm,
429                                 const MCAsmLayout *Layout,
430                                 const SectionAddrMap *Addrs) const {
431   // FIXME: The use if InSet = Addrs is a hack. Setting InSet causes us
432   // absolutize differences across sections and that is what the MachO writer
433   // uses Addrs for.
434   return evaluateAsAbsolute(Res, Asm, Layout, Addrs, Addrs);
435 }
436
437 bool MCExpr::evaluateAsAbsolute(int64_t &Res, const MCAssembler *Asm,
438                                 const MCAsmLayout *Layout,
439                                 const SectionAddrMap *Addrs, bool InSet) const {
440   MCValue Value;
441
442   // Fast path constants.
443   if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(this)) {
444     Res = CE->getValue();
445     return true;
446   }
447
448   bool IsRelocatable =
449       evaluateAsRelocatableImpl(Value, Asm, Layout, nullptr, Addrs, InSet);
450
451   // Record the current value.
452   Res = Value.getConstant();
453
454   return IsRelocatable && Value.isAbsolute();
455 }
456
457 /// \brief Helper method for \see EvaluateSymbolAdd().
458 static void AttemptToFoldSymbolOffsetDifference(
459     const MCAssembler *Asm, const MCAsmLayout *Layout,
460     const SectionAddrMap *Addrs, bool InSet, const MCSymbolRefExpr *&A,
461     const MCSymbolRefExpr *&B, int64_t &Addend) {
462   if (!A || !B)
463     return;
464
465   const MCSymbol &SA = A->getSymbol();
466   const MCSymbol &SB = B->getSymbol();
467
468   if (SA.isUndefined() || SB.isUndefined())
469     return;
470
471   if (!Asm->getWriter().IsSymbolRefDifferenceFullyResolved(*Asm, A, B, InSet))
472     return;
473
474   if (SA.getFragment() == SB.getFragment()) {
475     Addend += (SA.getOffset() - SB.getOffset());
476
477     // Pointers to Thumb symbols need to have their low-bit set to allow
478     // for interworking.
479     if (Asm->isThumbFunc(&SA))
480       Addend |= 1;
481
482     // Clear the symbol expr pointers to indicate we have folded these
483     // operands.
484     A = B = nullptr;
485     return;
486   }
487
488   if (!Layout)
489     return;
490
491   const MCSection &SecA = *SA.getFragment()->getParent();
492   const MCSection &SecB = *SB.getFragment()->getParent();
493
494   if ((&SecA != &SecB) && !Addrs)
495     return;
496
497   // Eagerly evaluate.
498   Addend += Layout->getSymbolOffset(A->getSymbol()) -
499             Layout->getSymbolOffset(B->getSymbol());
500   if (Addrs && (&SecA != &SecB))
501     Addend += (Addrs->lookup(&SecA) - Addrs->lookup(&SecB));
502
503   // Pointers to Thumb symbols need to have their low-bit set to allow
504   // for interworking.
505   if (Asm->isThumbFunc(&SA))
506     Addend |= 1;
507
508   // Clear the symbol expr pointers to indicate we have folded these
509   // operands.
510   A = B = nullptr;
511 }
512
513 /// \brief Evaluate the result of an add between (conceptually) two MCValues.
514 ///
515 /// This routine conceptually attempts to construct an MCValue:
516 ///   Result = (Result_A - Result_B + Result_Cst)
517 /// from two MCValue's LHS and RHS where
518 ///   Result = LHS + RHS
519 /// and
520 ///   Result = (LHS_A - LHS_B + LHS_Cst) + (RHS_A - RHS_B + RHS_Cst).
521 ///
522 /// This routine attempts to aggresively fold the operands such that the result
523 /// is representable in an MCValue, but may not always succeed.
524 ///
525 /// \returns True on success, false if the result is not representable in an
526 /// MCValue.
527
528 /// NOTE: It is really important to have both the Asm and Layout arguments.
529 /// They might look redundant, but this function can be used before layout
530 /// is done (see the object streamer for example) and having the Asm argument
531 /// lets us avoid relaxations early.
532 static bool
533 EvaluateSymbolicAdd(const MCAssembler *Asm, const MCAsmLayout *Layout,
534                     const SectionAddrMap *Addrs, bool InSet, const MCValue &LHS,
535                     const MCSymbolRefExpr *RHS_A, const MCSymbolRefExpr *RHS_B,
536                     int64_t RHS_Cst, MCValue &Res) {
537   // FIXME: This routine (and other evaluation parts) are *incredibly* sloppy
538   // about dealing with modifiers. This will ultimately bite us, one day.
539   const MCSymbolRefExpr *LHS_A = LHS.getSymA();
540   const MCSymbolRefExpr *LHS_B = LHS.getSymB();
541   int64_t LHS_Cst = LHS.getConstant();
542
543   // Fold the result constant immediately.
544   int64_t Result_Cst = LHS_Cst + RHS_Cst;
545
546   assert((!Layout || Asm) &&
547          "Must have an assembler object if layout is given!");
548
549   // If we have a layout, we can fold resolved differences.
550   if (Asm) {
551     // First, fold out any differences which are fully resolved. By
552     // reassociating terms in
553     //   Result = (LHS_A - LHS_B + LHS_Cst) + (RHS_A - RHS_B + RHS_Cst).
554     // we have the four possible differences:
555     //   (LHS_A - LHS_B),
556     //   (LHS_A - RHS_B),
557     //   (RHS_A - LHS_B),
558     //   (RHS_A - RHS_B).
559     // Since we are attempting to be as aggressive as possible about folding, we
560     // attempt to evaluate each possible alternative.
561     AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, LHS_A, LHS_B,
562                                         Result_Cst);
563     AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, LHS_A, RHS_B,
564                                         Result_Cst);
565     AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, RHS_A, LHS_B,
566                                         Result_Cst);
567     AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, RHS_A, RHS_B,
568                                         Result_Cst);
569   }
570
571   // We can't represent the addition or subtraction of two symbols.
572   if ((LHS_A && RHS_A) || (LHS_B && RHS_B))
573     return false;
574
575   // At this point, we have at most one additive symbol and one subtractive
576   // symbol -- find them.
577   const MCSymbolRefExpr *A = LHS_A ? LHS_A : RHS_A;
578   const MCSymbolRefExpr *B = LHS_B ? LHS_B : RHS_B;
579
580   // If we have a negated symbol, then we must have also have a non-negated
581   // symbol in order to encode the expression.
582   if (B && !A)
583     return false;
584
585   Res = MCValue::get(A, B, Result_Cst);
586   return true;
587 }
588
589 bool MCExpr::evaluateAsRelocatable(MCValue &Res,
590                                    const MCAsmLayout *Layout,
591                                    const MCFixup *Fixup) const {
592   MCAssembler *Assembler = Layout ? &Layout->getAssembler() : nullptr;
593   return evaluateAsRelocatableImpl(Res, Assembler, Layout, Fixup, nullptr,
594                                    false);
595 }
596
597 bool MCExpr::evaluateAsValue(MCValue &Res, const MCAsmLayout &Layout) const {
598   MCAssembler *Assembler = &Layout.getAssembler();
599   return evaluateAsRelocatableImpl(Res, Assembler, &Layout, nullptr, nullptr,
600                                    true);
601 }
602
603 static bool canExpand(const MCSymbol &Sym, const MCAssembler *Asm, bool InSet) {
604   if (InSet)
605     return true;
606   if (!Asm)
607     return false;
608   return !Asm->getWriter().isWeak(Sym);
609 }
610
611 bool MCExpr::evaluateAsRelocatableImpl(MCValue &Res, const MCAssembler *Asm,
612                                        const MCAsmLayout *Layout,
613                                        const MCFixup *Fixup,
614                                        const SectionAddrMap *Addrs,
615                                        bool InSet) const {
616   ++stats::MCExprEvaluate;
617
618   switch (getKind()) {
619   case Target:
620     return cast<MCTargetExpr>(this)->evaluateAsRelocatableImpl(Res, Layout,
621                                                                Fixup);
622
623   case Constant:
624     Res = MCValue::get(cast<MCConstantExpr>(this)->getValue());
625     return true;
626
627   case SymbolRef: {
628     const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(this);
629     const MCSymbol &Sym = SRE->getSymbol();
630
631     // Evaluate recursively if this is a variable.
632     if (Sym.isVariable() && SRE->getKind() == MCSymbolRefExpr::VK_None &&
633         canExpand(Sym, Asm, InSet)) {
634       bool IsMachO = SRE->hasSubsectionsViaSymbols();
635       if (Sym.getVariableValue()->evaluateAsRelocatableImpl(
636               Res, Asm, Layout, Fixup, Addrs, InSet || IsMachO)) {
637         if (!IsMachO)
638           return true;
639
640         const MCSymbolRefExpr *A = Res.getSymA();
641         const MCSymbolRefExpr *B = Res.getSymB();
642         // FIXME: This is small hack. Given
643         // a = b + 4
644         // .long a
645         // the OS X assembler will completely drop the 4. We should probably
646         // include it in the relocation or produce an error if that is not
647         // possible.
648         if (!A && !B)
649           return true;
650       }
651     }
652
653     Res = MCValue::get(SRE, nullptr, 0);
654     return true;
655   }
656
657   case Unary: {
658     const MCUnaryExpr *AUE = cast<MCUnaryExpr>(this);
659     MCValue Value;
660
661     if (!AUE->getSubExpr()->evaluateAsRelocatableImpl(Value, Asm, Layout, Fixup,
662                                                       Addrs, InSet))
663       return false;
664
665     switch (AUE->getOpcode()) {
666     case MCUnaryExpr::LNot:
667       if (!Value.isAbsolute())
668         return false;
669       Res = MCValue::get(!Value.getConstant());
670       break;
671     case MCUnaryExpr::Minus:
672       /// -(a - b + const) ==> (b - a - const)
673       if (Value.getSymA() && !Value.getSymB())
674         return false;
675       Res = MCValue::get(Value.getSymB(), Value.getSymA(),
676                          -Value.getConstant());
677       break;
678     case MCUnaryExpr::Not:
679       if (!Value.isAbsolute())
680         return false;
681       Res = MCValue::get(~Value.getConstant());
682       break;
683     case MCUnaryExpr::Plus:
684       Res = Value;
685       break;
686     }
687
688     return true;
689   }
690
691   case Binary: {
692     const MCBinaryExpr *ABE = cast<MCBinaryExpr>(this);
693     MCValue LHSValue, RHSValue;
694
695     if (!ABE->getLHS()->evaluateAsRelocatableImpl(LHSValue, Asm, Layout, Fixup,
696                                                   Addrs, InSet) ||
697         !ABE->getRHS()->evaluateAsRelocatableImpl(RHSValue, Asm, Layout, Fixup,
698                                                   Addrs, InSet))
699       return false;
700
701     // We only support a few operations on non-constant expressions, handle
702     // those first.
703     if (!LHSValue.isAbsolute() || !RHSValue.isAbsolute()) {
704       switch (ABE->getOpcode()) {
705       default:
706         return false;
707       case MCBinaryExpr::Sub:
708         // Negate RHS and add.
709         return EvaluateSymbolicAdd(Asm, Layout, Addrs, InSet, LHSValue,
710                                    RHSValue.getSymB(), RHSValue.getSymA(),
711                                    -RHSValue.getConstant(), Res);
712
713       case MCBinaryExpr::Add:
714         return EvaluateSymbolicAdd(Asm, Layout, Addrs, InSet, LHSValue,
715                                    RHSValue.getSymA(), RHSValue.getSymB(),
716                                    RHSValue.getConstant(), Res);
717       }
718     }
719
720     // FIXME: We need target hooks for the evaluation. It may be limited in
721     // width, and gas defines the result of comparisons differently from
722     // Apple as.
723     int64_t LHS = LHSValue.getConstant(), RHS = RHSValue.getConstant();
724     int64_t Result = 0;
725     switch (ABE->getOpcode()) {
726     case MCBinaryExpr::AShr: Result = LHS >> RHS; break;
727     case MCBinaryExpr::Add:  Result = LHS + RHS; break;
728     case MCBinaryExpr::And:  Result = LHS & RHS; break;
729     case MCBinaryExpr::Div:  Result = LHS / RHS; break;
730     case MCBinaryExpr::EQ:   Result = LHS == RHS; break;
731     case MCBinaryExpr::GT:   Result = LHS > RHS; break;
732     case MCBinaryExpr::GTE:  Result = LHS >= RHS; break;
733     case MCBinaryExpr::LAnd: Result = LHS && RHS; break;
734     case MCBinaryExpr::LOr:  Result = LHS || RHS; break;
735     case MCBinaryExpr::LShr: Result = uint64_t(LHS) >> uint64_t(RHS); break;
736     case MCBinaryExpr::LT:   Result = LHS < RHS; break;
737     case MCBinaryExpr::LTE:  Result = LHS <= RHS; break;
738     case MCBinaryExpr::Mod:  Result = LHS % RHS; break;
739     case MCBinaryExpr::Mul:  Result = LHS * RHS; break;
740     case MCBinaryExpr::NE:   Result = LHS != RHS; break;
741     case MCBinaryExpr::Or:   Result = LHS | RHS; break;
742     case MCBinaryExpr::Shl:  Result = LHS << RHS; break;
743     case MCBinaryExpr::Sub:  Result = LHS - RHS; break;
744     case MCBinaryExpr::Xor:  Result = LHS ^ RHS; break;
745     }
746
747     Res = MCValue::get(Result);
748     return true;
749   }
750   }
751
752   llvm_unreachable("Invalid assembly expression kind!");
753 }
754
755 MCSection *MCExpr::findAssociatedSection() const {
756   switch (getKind()) {
757   case Target:
758     // We never look through target specific expressions.
759     return cast<MCTargetExpr>(this)->findAssociatedSection();
760
761   case Constant:
762     return MCSymbol::AbsolutePseudoSection;
763
764   case SymbolRef: {
765     const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(this);
766     const MCSymbol &Sym = SRE->getSymbol();
767
768     if (Sym.isDefined())
769       return &Sym.getSection();
770
771     return nullptr;
772   }
773
774   case Unary:
775     return cast<MCUnaryExpr>(this)->getSubExpr()->findAssociatedSection();
776
777   case Binary: {
778     const MCBinaryExpr *BE = cast<MCBinaryExpr>(this);
779     MCSection *LHS_S = BE->getLHS()->findAssociatedSection();
780     MCSection *RHS_S = BE->getRHS()->findAssociatedSection();
781
782     // If either section is absolute, return the other.
783     if (LHS_S == MCSymbol::AbsolutePseudoSection)
784       return RHS_S;
785     if (RHS_S == MCSymbol::AbsolutePseudoSection)
786       return LHS_S;
787
788     // Not always correct, but probably the best we can do without more context.
789     if (BE->getOpcode() == MCBinaryExpr::Sub)
790       return MCSymbol::AbsolutePseudoSection;
791
792     // Otherwise, return the first non-null section.
793     return LHS_S ? LHS_S : RHS_S;
794   }
795   }
796
797   llvm_unreachable("Invalid assembly expression kind!");
798 }