MC/ARM/AsmParser: Split out SplitMnemonicAndCC().
[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 #define DEBUG_TYPE "mcexpr"
11 #include "llvm/MC/MCExpr.h"
12 #include "llvm/ADT/Statistic.h"
13 #include "llvm/ADT/StringSwitch.h"
14 #include "llvm/MC/MCAsmLayout.h"
15 #include "llvm/MC/MCAssembler.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCSymbol.h"
18 #include "llvm/MC/MCValue.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include "llvm/Target/TargetAsmBackend.h"
22 using namespace llvm;
23
24 namespace {
25 namespace stats {
26 STATISTIC(MCExprEvaluate, "Number of MCExpr evaluations");
27 }
28 }
29
30 void MCExpr::print(raw_ostream &OS) const {
31   switch (getKind()) {
32   case MCExpr::Target:
33     return cast<MCTargetExpr>(this)->PrintImpl(OS);
34   case MCExpr::Constant:
35     OS << cast<MCConstantExpr>(*this).getValue();
36     return;
37
38   case MCExpr::SymbolRef: {
39     const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(*this);
40     const MCSymbol &Sym = SRE.getSymbol();
41     // Parenthesize names that start with $ so that they don't look like
42     // absolute names.
43     bool UseParens = Sym.getName()[0] == '$';
44
45     if (SRE.getKind() == MCSymbolRefExpr::VK_ARM_HI16 ||
46         SRE.getKind() == MCSymbolRefExpr::VK_ARM_LO16)
47       OS << MCSymbolRefExpr::getVariantKindName(SRE.getKind());
48
49     if (SRE.getKind() == MCSymbolRefExpr::VK_PPC_HA16 ||
50         SRE.getKind() == MCSymbolRefExpr::VK_PPC_LO16) {
51       OS << MCSymbolRefExpr::getVariantKindName(SRE.getKind());
52       UseParens = true;
53     }
54
55     if (UseParens)
56       OS << '(' << Sym << ')';
57     else
58       OS << Sym;
59
60     if (SRE.getKind() == MCSymbolRefExpr::VK_ARM_PLT ||
61         SRE.getKind() == MCSymbolRefExpr::VK_ARM_TLSGD ||
62         SRE.getKind() == MCSymbolRefExpr::VK_ARM_GOT ||
63         SRE.getKind() == MCSymbolRefExpr::VK_ARM_GOTOFF ||
64         SRE.getKind() == MCSymbolRefExpr::VK_ARM_TPOFF ||
65         SRE.getKind() == MCSymbolRefExpr::VK_ARM_GOTTPOFF)
66       OS << MCSymbolRefExpr::getVariantKindName(SRE.getKind());
67     else if (SRE.getKind() != MCSymbolRefExpr::VK_None &&
68              SRE.getKind() != MCSymbolRefExpr::VK_ARM_HI16 &&
69              SRE.getKind() != MCSymbolRefExpr::VK_ARM_LO16 &&
70              SRE.getKind() != MCSymbolRefExpr::VK_PPC_HA16 &&
71              SRE.getKind() != MCSymbolRefExpr::VK_PPC_LO16)
72       OS << '@' << MCSymbolRefExpr::getVariantKindName(SRE.getKind());
73
74     return;
75   }
76
77   case MCExpr::Unary: {
78     const MCUnaryExpr &UE = cast<MCUnaryExpr>(*this);
79     switch (UE.getOpcode()) {
80     default: assert(0 && "Invalid opcode!");
81     case MCUnaryExpr::LNot:  OS << '!'; break;
82     case MCUnaryExpr::Minus: OS << '-'; break;
83     case MCUnaryExpr::Not:   OS << '~'; break;
84     case MCUnaryExpr::Plus:  OS << '+'; break;
85     }
86     OS << *UE.getSubExpr();
87     return;
88   }
89
90   case MCExpr::Binary: {
91     const MCBinaryExpr &BE = cast<MCBinaryExpr>(*this);
92
93     // Only print parens around the LHS if it is non-trivial.
94     if (isa<MCConstantExpr>(BE.getLHS()) || isa<MCSymbolRefExpr>(BE.getLHS())) {
95       OS << *BE.getLHS();
96     } else {
97       OS << '(' << *BE.getLHS() << ')';
98     }
99
100     switch (BE.getOpcode()) {
101     default: assert(0 && "Invalid opcode!");
102     case MCBinaryExpr::Add:
103       // Print "X-42" instead of "X+-42".
104       if (const MCConstantExpr *RHSC = dyn_cast<MCConstantExpr>(BE.getRHS())) {
105         if (RHSC->getValue() < 0) {
106           OS << RHSC->getValue();
107           return;
108         }
109       }
110
111       OS <<  '+';
112       break;
113     case MCBinaryExpr::And:  OS <<  '&'; break;
114     case MCBinaryExpr::Div:  OS <<  '/'; break;
115     case MCBinaryExpr::EQ:   OS << "=="; break;
116     case MCBinaryExpr::GT:   OS <<  '>'; break;
117     case MCBinaryExpr::GTE:  OS << ">="; break;
118     case MCBinaryExpr::LAnd: OS << "&&"; break;
119     case MCBinaryExpr::LOr:  OS << "||"; break;
120     case MCBinaryExpr::LT:   OS <<  '<'; break;
121     case MCBinaryExpr::LTE:  OS << "<="; break;
122     case MCBinaryExpr::Mod:  OS <<  '%'; break;
123     case MCBinaryExpr::Mul:  OS <<  '*'; break;
124     case MCBinaryExpr::NE:   OS << "!="; break;
125     case MCBinaryExpr::Or:   OS <<  '|'; break;
126     case MCBinaryExpr::Shl:  OS << "<<"; break;
127     case MCBinaryExpr::Shr:  OS << ">>"; break;
128     case MCBinaryExpr::Sub:  OS <<  '-'; break;
129     case MCBinaryExpr::Xor:  OS <<  '^'; break;
130     }
131
132     // Only print parens around the LHS if it is non-trivial.
133     if (isa<MCConstantExpr>(BE.getRHS()) || isa<MCSymbolRefExpr>(BE.getRHS())) {
134       OS << *BE.getRHS();
135     } else {
136       OS << '(' << *BE.getRHS() << ')';
137     }
138     return;
139   }
140   }
141
142   assert(0 && "Invalid expression kind!");
143 }
144
145 void MCExpr::dump() const {
146   print(dbgs());
147   dbgs() << '\n';
148 }
149
150 /* *** */
151
152 const MCBinaryExpr *MCBinaryExpr::Create(Opcode Opc, const MCExpr *LHS,
153                                          const MCExpr *RHS, MCContext &Ctx) {
154   return new (Ctx) MCBinaryExpr(Opc, LHS, RHS);
155 }
156
157 const MCUnaryExpr *MCUnaryExpr::Create(Opcode Opc, const MCExpr *Expr,
158                                        MCContext &Ctx) {
159   return new (Ctx) MCUnaryExpr(Opc, Expr);
160 }
161
162 const MCConstantExpr *MCConstantExpr::Create(int64_t Value, MCContext &Ctx) {
163   return new (Ctx) MCConstantExpr(Value);
164 }
165
166 /* *** */
167
168 const MCSymbolRefExpr *MCSymbolRefExpr::Create(const MCSymbol *Sym,
169                                                VariantKind Kind,
170                                                MCContext &Ctx) {
171   return new (Ctx) MCSymbolRefExpr(Sym, Kind);
172 }
173
174 const MCSymbolRefExpr *MCSymbolRefExpr::Create(StringRef Name, VariantKind Kind,
175                                                MCContext &Ctx) {
176   return Create(Ctx.GetOrCreateSymbol(Name), Kind, Ctx);
177 }
178
179 StringRef MCSymbolRefExpr::getVariantKindName(VariantKind Kind) {
180   switch (Kind) {
181   default:
182   case VK_Invalid: return "<<invalid>>";
183   case VK_None: return "<<none>>";
184
185   case VK_GOT: return "GOT";
186   case VK_GOTOFF: return "GOTOFF";
187   case VK_GOTPCREL: return "GOTPCREL";
188   case VK_GOTTPOFF: return "GOTTPOFF";
189   case VK_INDNTPOFF: return "INDNTPOFF";
190   case VK_NTPOFF: return "NTPOFF";
191   case VK_GOTNTPOFF: return "GOTNTPOFF";
192   case VK_PLT: return "PLT";
193   case VK_TLSGD: return "TLSGD";
194   case VK_TLSLD: return "TLSLD";
195   case VK_TLSLDM: return "TLSLDM";
196   case VK_TPOFF: return "TPOFF";
197   case VK_DTPOFF: return "DTPOFF";
198   case VK_TLVP: return "TLVP";
199   case VK_ARM_HI16: return ":upper16:";
200   case VK_ARM_LO16: return ":lower16:";
201   case VK_ARM_PLT: return "(PLT)";
202   case VK_ARM_GOT: return "(GOT)";
203   case VK_ARM_GOTOFF: return "(GOTOFF)";
204   case VK_ARM_TPOFF: return "(tpoff)";
205   case VK_ARM_GOTTPOFF: return "(gottpoff)";
206   case VK_ARM_TLSGD: return "(tlsgd)";
207   case VK_PPC_TOC: return "toc";
208   case VK_PPC_HA16: return "ha16";
209   case VK_PPC_LO16: return "lo16";
210   }
211 }
212
213 MCSymbolRefExpr::VariantKind
214 MCSymbolRefExpr::getVariantKindForName(StringRef Name) {
215   return StringSwitch<VariantKind>(Name)
216     .Case("GOT", VK_GOT)
217     .Case("GOTOFF", VK_GOTOFF)
218     .Case("GOTPCREL", VK_GOTPCREL)
219     .Case("GOTTPOFF", VK_GOTTPOFF)
220     .Case("INDNTPOFF", VK_INDNTPOFF)
221     .Case("NTPOFF", VK_NTPOFF)
222     .Case("GOTNTPOFF", VK_GOTNTPOFF)
223     .Case("PLT", VK_PLT)
224     .Case("TLSGD", VK_TLSGD)
225     .Case("TLSLD", VK_TLSLD)
226     .Case("TLSLDM", VK_TLSLDM)
227     .Case("TPOFF", VK_TPOFF)
228     .Case("DTPOFF", VK_DTPOFF)
229     .Case("TLVP", VK_TLVP)
230     .Default(VK_Invalid);
231 }
232
233 /* *** */
234
235 void MCTargetExpr::Anchor() {}
236
237 /* *** */
238
239 bool MCExpr::EvaluateAsAbsolute(int64_t &Res) const {
240   return EvaluateAsAbsolute(Res, 0, 0, 0);
241 }
242
243 bool MCExpr::EvaluateAsAbsolute(int64_t &Res,
244                                 const MCAsmLayout &Layout) const {
245   return EvaluateAsAbsolute(Res, &Layout.getAssembler(), &Layout, 0);
246 }
247
248 bool MCExpr::EvaluateAsAbsolute(int64_t &Res,
249                                 const MCAsmLayout &Layout,
250                                 const SectionAddrMap &Addrs) const {
251   return EvaluateAsAbsolute(Res, &Layout.getAssembler(), &Layout, &Addrs);
252 }
253
254 bool MCExpr::EvaluateAsAbsolute(int64_t &Res, const MCAssembler &Asm) const {
255   return EvaluateAsAbsolute(Res, &Asm, 0, 0);
256 }
257
258 bool MCExpr::EvaluateAsAbsolute(int64_t &Res, const MCAssembler *Asm,
259                                 const MCAsmLayout *Layout,
260                                 const SectionAddrMap *Addrs) const {
261   MCValue Value;
262
263   // Fast path constants.
264   if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(this)) {
265     Res = CE->getValue();
266     return true;
267   }
268
269   // FIXME: The use if InSet = Addrs is a hack. Setting InSet causes us
270   // absolutize differences across sections and that is what the MachO writer
271   // uses Addrs for.
272   bool IsRelocatable =
273     EvaluateAsRelocatableImpl(Value, Asm, Layout, Addrs, /*InSet*/ Addrs);
274
275   // Record the current value.
276   Res = Value.getConstant();
277
278   return IsRelocatable && Value.isAbsolute();
279 }
280
281 /// \brief Helper method for \see EvaluateSymbolAdd().
282 static void AttemptToFoldSymbolOffsetDifference(const MCAssembler *Asm,
283                                                 const MCAsmLayout *Layout,
284                                                 const SectionAddrMap *Addrs,
285                                                 bool InSet,
286                                                 const MCSymbolRefExpr *&A,
287                                                 const MCSymbolRefExpr *&B,
288                                                 int64_t &Addend) {
289   if (!A || !B)
290     return;
291
292   const MCSymbol &SA = A->getSymbol();
293   const MCSymbol &SB = B->getSymbol();
294
295   if (SA.isUndefined() || SB.isUndefined())
296     return;
297
298   if (!Asm->getWriter().IsSymbolRefDifferenceFullyResolved(*Asm, A, B, InSet))
299     return;
300
301   MCSymbolData &AD = Asm->getSymbolData(SA);
302   MCSymbolData &BD = Asm->getSymbolData(SB);
303
304   if (AD.getFragment() == BD.getFragment()) {
305     Addend += (AD.getOffset() - BD.getOffset());
306
307     // Clear the symbol expr pointers to indicate we have folded these
308     // operands.
309     A = B = 0;
310     return;
311   }
312
313   if (!Layout)
314     return;
315
316   const MCSectionData &SecA = *AD.getFragment()->getParent();
317   const MCSectionData &SecB = *BD.getFragment()->getParent();
318
319   if ((&SecA != &SecB) && !Addrs)
320     return;
321
322   // Eagerly evaluate.
323   Addend += (Layout->getSymbolOffset(&Asm->getSymbolData(A->getSymbol())) -
324              Layout->getSymbolOffset(&Asm->getSymbolData(B->getSymbol())));
325   if (Addrs && (&SecA != &SecB))
326     Addend += (Addrs->lookup(&SecA) - Addrs->lookup(&SecB));
327
328   // Clear the symbol expr pointers to indicate we have folded these
329   // operands.
330   A = B = 0;
331 }
332
333 /// \brief Evaluate the result of an add between (conceptually) two MCValues.
334 ///
335 /// This routine conceptually attempts to construct an MCValue:
336 ///   Result = (Result_A - Result_B + Result_Cst)
337 /// from two MCValue's LHS and RHS where
338 ///   Result = LHS + RHS
339 /// and
340 ///   Result = (LHS_A - LHS_B + LHS_Cst) + (RHS_A - RHS_B + RHS_Cst).
341 ///
342 /// This routine attempts to aggresively fold the operands such that the result
343 /// is representable in an MCValue, but may not always succeed.
344 ///
345 /// \returns True on success, false if the result is not representable in an
346 /// MCValue.
347
348 /// NOTE: It is really important to have both the Asm and Layout arguments.
349 /// They might look redundant, but this function can be used before layout
350 /// is done (see the object streamer for example) and having the Asm argument
351 /// lets us avoid relaxations early.
352 static bool EvaluateSymbolicAdd(const MCAssembler *Asm,
353                                 const MCAsmLayout *Layout,
354                                 const SectionAddrMap *Addrs,
355                                 bool InSet,
356                                 const MCValue &LHS,const MCSymbolRefExpr *RHS_A,
357                                 const MCSymbolRefExpr *RHS_B, int64_t RHS_Cst,
358                                 MCValue &Res) {
359   // FIXME: This routine (and other evaluation parts) are *incredibly* sloppy
360   // about dealing with modifiers. This will ultimately bite us, one day.
361   const MCSymbolRefExpr *LHS_A = LHS.getSymA();
362   const MCSymbolRefExpr *LHS_B = LHS.getSymB();
363   int64_t LHS_Cst = LHS.getConstant();
364
365   // Fold the result constant immediately.
366   int64_t Result_Cst = LHS_Cst + RHS_Cst;
367
368   assert((!Layout || Asm) &&
369          "Must have an assembler object if layout is given!");
370
371   // If we have a layout, we can fold resolved differences.
372   if (Asm) {
373     // First, fold out any differences which are fully resolved. By
374     // reassociating terms in
375     //   Result = (LHS_A - LHS_B + LHS_Cst) + (RHS_A - RHS_B + RHS_Cst).
376     // we have the four possible differences:
377     //   (LHS_A - LHS_B),
378     //   (LHS_A - RHS_B),
379     //   (RHS_A - LHS_B),
380     //   (RHS_A - RHS_B).
381     // Since we are attempting to be as aggresive as possible about folding, we
382     // attempt to evaluate each possible alternative.
383     AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, LHS_A, LHS_B,
384                                         Result_Cst);
385     AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, LHS_A, RHS_B,
386                                         Result_Cst);
387     AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, RHS_A, LHS_B,
388                                         Result_Cst);
389     AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, RHS_A, RHS_B,
390                                         Result_Cst);
391   }
392
393   // We can't represent the addition or subtraction of two symbols.
394   if ((LHS_A && RHS_A) || (LHS_B && RHS_B))
395     return false;
396
397   // At this point, we have at most one additive symbol and one subtractive
398   // symbol -- find them.
399   const MCSymbolRefExpr *A = LHS_A ? LHS_A : RHS_A;
400   const MCSymbolRefExpr *B = LHS_B ? LHS_B : RHS_B;
401
402   // If we have a negated symbol, then we must have also have a non-negated
403   // symbol in order to encode the expression.
404   if (B && !A)
405     return false;
406
407   Res = MCValue::get(A, B, Result_Cst);
408   return true;
409 }
410
411 bool MCExpr::EvaluateAsRelocatable(MCValue &Res,
412                                    const MCAsmLayout &Layout) const {
413   return EvaluateAsRelocatableImpl(Res, &Layout.getAssembler(), &Layout,
414                                    0, false);
415 }
416
417 bool MCExpr::EvaluateAsRelocatableImpl(MCValue &Res,
418                                        const MCAssembler *Asm,
419                                        const MCAsmLayout *Layout,
420                                        const SectionAddrMap *Addrs,
421                                        bool InSet) const {
422   ++stats::MCExprEvaluate;
423
424   switch (getKind()) {
425   case Target:
426     return cast<MCTargetExpr>(this)->EvaluateAsRelocatableImpl(Res, Layout);
427
428   case Constant:
429     Res = MCValue::get(cast<MCConstantExpr>(this)->getValue());
430     return true;
431
432   case SymbolRef: {
433     const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(this);
434     const MCSymbol &Sym = SRE->getSymbol();
435
436     // Evaluate recursively if this is a variable.
437     if (Sym.isVariable() && SRE->getKind() == MCSymbolRefExpr::VK_None) {
438       bool Ret = Sym.getVariableValue()->EvaluateAsRelocatableImpl(Res, Asm,
439                                                                    Layout,
440                                                                    Addrs,
441                                                                    true);
442       // If we failed to simplify this to a constant, let the target
443       // handle it.
444       if (Ret && !Res.getSymA() && !Res.getSymB())
445         return true;
446     }
447
448     Res = MCValue::get(SRE, 0, 0);
449     return true;
450   }
451
452   case Unary: {
453     const MCUnaryExpr *AUE = cast<MCUnaryExpr>(this);
454     MCValue Value;
455
456     if (!AUE->getSubExpr()->EvaluateAsRelocatableImpl(Value, Asm, Layout,
457                                                       Addrs, InSet))
458       return false;
459
460     switch (AUE->getOpcode()) {
461     case MCUnaryExpr::LNot:
462       if (!Value.isAbsolute())
463         return false;
464       Res = MCValue::get(!Value.getConstant());
465       break;
466     case MCUnaryExpr::Minus:
467       /// -(a - b + const) ==> (b - a - const)
468       if (Value.getSymA() && !Value.getSymB())
469         return false;
470       Res = MCValue::get(Value.getSymB(), Value.getSymA(),
471                          -Value.getConstant());
472       break;
473     case MCUnaryExpr::Not:
474       if (!Value.isAbsolute())
475         return false;
476       Res = MCValue::get(~Value.getConstant());
477       break;
478     case MCUnaryExpr::Plus:
479       Res = Value;
480       break;
481     }
482
483     return true;
484   }
485
486   case Binary: {
487     const MCBinaryExpr *ABE = cast<MCBinaryExpr>(this);
488     MCValue LHSValue, RHSValue;
489
490     if (!ABE->getLHS()->EvaluateAsRelocatableImpl(LHSValue, Asm, Layout,
491                                                   Addrs, InSet) ||
492         !ABE->getRHS()->EvaluateAsRelocatableImpl(RHSValue, Asm, Layout,
493                                                   Addrs, InSet))
494       return false;
495
496     // We only support a few operations on non-constant expressions, handle
497     // those first.
498     if (!LHSValue.isAbsolute() || !RHSValue.isAbsolute()) {
499       switch (ABE->getOpcode()) {
500       default:
501         return false;
502       case MCBinaryExpr::Sub:
503         // Negate RHS and add.
504         return EvaluateSymbolicAdd(Asm, Layout, Addrs, InSet, LHSValue,
505                                    RHSValue.getSymB(), RHSValue.getSymA(),
506                                    -RHSValue.getConstant(),
507                                    Res);
508
509       case MCBinaryExpr::Add:
510         return EvaluateSymbolicAdd(Asm, Layout, Addrs, InSet, LHSValue,
511                                    RHSValue.getSymA(), RHSValue.getSymB(),
512                                    RHSValue.getConstant(),
513                                    Res);
514       }
515     }
516
517     // FIXME: We need target hooks for the evaluation. It may be limited in
518     // width, and gas defines the result of comparisons and right shifts
519     // differently from Apple as.
520     int64_t LHS = LHSValue.getConstant(), RHS = RHSValue.getConstant();
521     int64_t Result = 0;
522     switch (ABE->getOpcode()) {
523     case MCBinaryExpr::Add:  Result = LHS + RHS; break;
524     case MCBinaryExpr::And:  Result = LHS & RHS; break;
525     case MCBinaryExpr::Div:  Result = LHS / RHS; break;
526     case MCBinaryExpr::EQ:   Result = LHS == RHS; break;
527     case MCBinaryExpr::GT:   Result = LHS > RHS; break;
528     case MCBinaryExpr::GTE:  Result = LHS >= RHS; break;
529     case MCBinaryExpr::LAnd: Result = LHS && RHS; break;
530     case MCBinaryExpr::LOr:  Result = LHS || RHS; break;
531     case MCBinaryExpr::LT:   Result = LHS < RHS; break;
532     case MCBinaryExpr::LTE:  Result = LHS <= RHS; break;
533     case MCBinaryExpr::Mod:  Result = LHS % RHS; break;
534     case MCBinaryExpr::Mul:  Result = LHS * RHS; break;
535     case MCBinaryExpr::NE:   Result = LHS != RHS; break;
536     case MCBinaryExpr::Or:   Result = LHS | RHS; break;
537     case MCBinaryExpr::Shl:  Result = LHS << RHS; break;
538     case MCBinaryExpr::Shr:  Result = LHS >> RHS; break;
539     case MCBinaryExpr::Sub:  Result = LHS - RHS; break;
540     case MCBinaryExpr::Xor:  Result = LHS ^ RHS; break;
541     }
542
543     Res = MCValue::get(Result);
544     return true;
545   }
546   }
547
548   assert(0 && "Invalid assembly expression kind!");
549   return false;
550 }