OSDN Git Service

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