1 //===- llvm/InlineAsm.h - Class to represent inline asm strings -*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This class represents the inline asm strings, which are Value*'s that are
10 // used as the callee operand of call instructions.  InlineAsm's are uniqued
11 // like constants, and created via InlineAsm::get(...).
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_IR_INLINEASM_H
16 #define LLVM_IR_INLINEASM_H
17 
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/IR/Value.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include <cassert>
22 #include <string>
23 #include <vector>
24 
25 namespace llvm {
26 
27 class FunctionType;
28 class PointerType;
29 template <class ConstantClass> class ConstantUniqueMap;
30 
31 class InlineAsm final : public Value {
32 public:
33   enum AsmDialect {
34     AD_ATT,
35     AD_Intel
36   };
37 
38 private:
39   friend struct InlineAsmKeyType;
40   friend class ConstantUniqueMap<InlineAsm>;
41 
42   std::string AsmString, Constraints;
43   FunctionType *FTy;
44   bool HasSideEffects;
45   bool IsAlignStack;
46   AsmDialect Dialect;
47   bool CanThrow;
48 
49   InlineAsm(FunctionType *Ty, const std::string &AsmString,
50             const std::string &Constraints, bool hasSideEffects,
51             bool isAlignStack, AsmDialect asmDialect, bool canThrow);
52 
53   /// When the ConstantUniqueMap merges two types and makes two InlineAsms
54   /// identical, it destroys one of them with this method.
55   void destroyConstant();
56 
57 public:
58   InlineAsm(const InlineAsm &) = delete;
59   InlineAsm &operator=(const InlineAsm &) = delete;
60 
61   /// InlineAsm::get - Return the specified uniqued inline asm string.
62   ///
63   static InlineAsm *get(FunctionType *Ty, StringRef AsmString,
64                         StringRef Constraints, bool hasSideEffects,
65                         bool isAlignStack = false,
66                         AsmDialect asmDialect = AD_ATT, bool canThrow = false);
67 
hasSideEffects()68   bool hasSideEffects() const { return HasSideEffects; }
isAlignStack()69   bool isAlignStack() const { return IsAlignStack; }
getDialect()70   AsmDialect getDialect() const { return Dialect; }
canThrow()71   bool canThrow() const { return CanThrow; }
72 
73   /// getType - InlineAsm's are always pointers.
74   ///
getType()75   PointerType *getType() const {
76     return reinterpret_cast<PointerType*>(Value::getType());
77   }
78 
79   /// getFunctionType - InlineAsm's are always pointers to functions.
80   ///
81   FunctionType *getFunctionType() const;
82 
getAsmString()83   const std::string &getAsmString() const { return AsmString; }
getConstraintString()84   const std::string &getConstraintString() const { return Constraints; }
85 
86   /// Verify - This static method can be used by the parser to check to see if
87   /// the specified constraint string is legal for the type.  This returns true
88   /// if legal, false if not.
89   ///
90   static bool Verify(FunctionType *Ty, StringRef Constraints);
91 
92   // Constraint String Parsing
93   enum ConstraintPrefix {
94     isInput,            // 'x'
95     isOutput,           // '=x'
96     isClobber           // '~x'
97   };
98 
99   using ConstraintCodeVector = std::vector<std::string>;
100 
101   struct SubConstraintInfo {
102     /// MatchingInput - If this is not -1, this is an output constraint where an
103     /// input constraint is required to match it (e.g. "0").  The value is the
104     /// constraint number that matches this one (for example, if this is
105     /// constraint #0 and constraint #4 has the value "0", this will be 4).
106     int MatchingInput = -1;
107 
108     /// Code - The constraint code, either the register name (in braces) or the
109     /// constraint letter/number.
110     ConstraintCodeVector Codes;
111 
112     /// Default constructor.
113     SubConstraintInfo() = default;
114   };
115 
116   using SubConstraintInfoVector = std::vector<SubConstraintInfo>;
117   struct ConstraintInfo;
118   using ConstraintInfoVector = std::vector<ConstraintInfo>;
119 
120   struct ConstraintInfo {
121     /// Type - The basic type of the constraint: input/output/clobber
122     ///
123     ConstraintPrefix Type = isInput;
124 
125     /// isEarlyClobber - "&": output operand writes result before inputs are all
126     /// read.  This is only ever set for an output operand.
127     bool isEarlyClobber = false;
128 
129     /// MatchingInput - If this is not -1, this is an output constraint where an
130     /// input constraint is required to match it (e.g. "0").  The value is the
131     /// constraint number that matches this one (for example, if this is
132     /// constraint #0 and constraint #4 has the value "0", this will be 4).
133     int MatchingInput = -1;
134 
135     /// hasMatchingInput - Return true if this is an output constraint that has
136     /// a matching input constraint.
hasMatchingInputConstraintInfo137     bool hasMatchingInput() const { return MatchingInput != -1; }
138 
139     /// isCommutative - This is set to true for a constraint that is commutative
140     /// with the next operand.
141     bool isCommutative = false;
142 
143     /// isIndirect - True if this operand is an indirect operand.  This means
144     /// that the address of the source or destination is present in the call
145     /// instruction, instead of it being returned or passed in explicitly.  This
146     /// is represented with a '*' in the asm string.
147     bool isIndirect = false;
148 
149     /// Code - The constraint code, either the register name (in braces) or the
150     /// constraint letter/number.
151     ConstraintCodeVector Codes;
152 
153     /// isMultipleAlternative - '|': has multiple-alternative constraints.
154     bool isMultipleAlternative = false;
155 
156     /// multipleAlternatives - If there are multiple alternative constraints,
157     /// this array will contain them.  Otherwise it will be empty.
158     SubConstraintInfoVector multipleAlternatives;
159 
160     /// The currently selected alternative constraint index.
161     unsigned currentAlternativeIndex = 0;
162 
163     /// Default constructor.
164     ConstraintInfo() = default;
165 
166     /// Parse - Analyze the specified string (e.g. "=*&{eax}") and fill in the
167     /// fields in this structure.  If the constraint string is not understood,
168     /// return true, otherwise return false.
169     bool Parse(StringRef Str, ConstraintInfoVector &ConstraintsSoFar);
170 
171     /// selectAlternative - Point this constraint to the alternative constraint
172     /// indicated by the index.
173     void selectAlternative(unsigned index);
174   };
175 
176   /// ParseConstraints - Split up the constraint string into the specific
177   /// constraints and their prefixes.  If this returns an empty vector, and if
178   /// the constraint string itself isn't empty, there was an error parsing.
179   static ConstraintInfoVector ParseConstraints(StringRef ConstraintString);
180 
181   /// ParseConstraints - Parse the constraints of this inlineasm object,
182   /// returning them the same way that ParseConstraints(str) does.
ParseConstraints()183   ConstraintInfoVector ParseConstraints() const {
184     return ParseConstraints(Constraints);
185   }
186 
187   // Methods for support type inquiry through isa, cast, and dyn_cast:
classof(const Value * V)188   static bool classof(const Value *V) {
189     return V->getValueID() == Value::InlineAsmVal;
190   }
191 
192   // These are helper methods for dealing with flags in the INLINEASM SDNode
193   // in the backend.
194   //
195   // The encoding of the flag word is currently:
196   //   Bits 2-0 - A Kind_* value indicating the kind of the operand.
197   //   Bits 15-3 - The number of SDNode operands associated with this inline
198   //               assembly operand.
199   //   If bit 31 is set:
200   //     Bit 30-16 - The operand number that this operand must match.
201   //                 When bits 2-0 are Kind_Mem, the Constraint_* value must be
202   //                 obtained from the flags for this operand number.
203   //   Else if bits 2-0 are Kind_Mem:
204   //     Bit 30-16 - A Constraint_* value indicating the original constraint
205   //                 code.
206   //   Else:
207   //     Bit 30-16 - The register class ID to use for the operand.
208 
209   enum : uint32_t {
210     // Fixed operands on an INLINEASM SDNode.
211     Op_InputChain = 0,
212     Op_AsmString = 1,
213     Op_MDNode = 2,
214     Op_ExtraInfo = 3,    // HasSideEffects, IsAlignStack, AsmDialect.
215     Op_FirstOperand = 4,
216 
217     // Fixed operands on an INLINEASM MachineInstr.
218     MIOp_AsmString = 0,
219     MIOp_ExtraInfo = 1,    // HasSideEffects, IsAlignStack, AsmDialect.
220     MIOp_FirstOperand = 2,
221 
222     // Interpretation of the MIOp_ExtraInfo bit field.
223     Extra_HasSideEffects = 1,
224     Extra_IsAlignStack = 2,
225     Extra_AsmDialect = 4,
226     Extra_MayLoad = 8,
227     Extra_MayStore = 16,
228     Extra_IsConvergent = 32,
229 
230     // Inline asm operands map to multiple SDNode / MachineInstr operands.
231     // The first operand is an immediate describing the asm operand, the low
232     // bits is the kind:
233     Kind_RegUse = 1,             // Input register, "r".
234     Kind_RegDef = 2,             // Output register, "=r".
235     Kind_RegDefEarlyClobber = 3, // Early-clobber output register, "=&r".
236     Kind_Clobber = 4,            // Clobbered register, "~r".
237     Kind_Imm = 5,                // Immediate.
238     Kind_Mem = 6,                // Memory operand, "m".
239 
240     // Memory constraint codes.
241     // These could be tablegenerated but there's little need to do that since
242     // there's plenty of space in the encoding to support the union of all
243     // constraint codes for all targets.
244     Constraint_Unknown = 0,
245     Constraint_es,
246     Constraint_i,
247     Constraint_m,
248     Constraint_o,
249     Constraint_v,
250     Constraint_A,
251     Constraint_Q,
252     Constraint_R,
253     Constraint_S,
254     Constraint_T,
255     Constraint_Um,
256     Constraint_Un,
257     Constraint_Uq,
258     Constraint_Us,
259     Constraint_Ut,
260     Constraint_Uv,
261     Constraint_Uy,
262     Constraint_X,
263     Constraint_Z,
264     Constraint_ZC,
265     Constraint_Zy,
266     Constraints_Max = Constraint_Zy,
267     Constraints_ShiftAmount = 16,
268 
269     Flag_MatchingOperand = 0x80000000
270   };
271 
getFlagWord(unsigned Kind,unsigned NumOps)272   static unsigned getFlagWord(unsigned Kind, unsigned NumOps) {
273     assert(((NumOps << 3) & ~0xffff) == 0 && "Too many inline asm operands!");
274     assert(Kind >= Kind_RegUse && Kind <= Kind_Mem && "Invalid Kind");
275     return Kind | (NumOps << 3);
276   }
277 
isRegDefKind(unsigned Flag)278   static bool isRegDefKind(unsigned Flag){ return getKind(Flag) == Kind_RegDef;}
isImmKind(unsigned Flag)279   static bool isImmKind(unsigned Flag) { return getKind(Flag) == Kind_Imm; }
isMemKind(unsigned Flag)280   static bool isMemKind(unsigned Flag) { return getKind(Flag) == Kind_Mem; }
isRegDefEarlyClobberKind(unsigned Flag)281   static bool isRegDefEarlyClobberKind(unsigned Flag) {
282     return getKind(Flag) == Kind_RegDefEarlyClobber;
283   }
isClobberKind(unsigned Flag)284   static bool isClobberKind(unsigned Flag) {
285     return getKind(Flag) == Kind_Clobber;
286   }
287 
288   /// getFlagWordForMatchingOp - Augment an existing flag word returned by
289   /// getFlagWord with information indicating that this input operand is tied
290   /// to a previous output operand.
getFlagWordForMatchingOp(unsigned InputFlag,unsigned MatchedOperandNo)291   static unsigned getFlagWordForMatchingOp(unsigned InputFlag,
292                                            unsigned MatchedOperandNo) {
293     assert(MatchedOperandNo <= 0x7fff && "Too big matched operand");
294     assert((InputFlag & ~0xffff) == 0 && "High bits already contain data");
295     return InputFlag | Flag_MatchingOperand | (MatchedOperandNo << 16);
296   }
297 
298   /// getFlagWordForRegClass - Augment an existing flag word returned by
299   /// getFlagWord with the required register class for the following register
300   /// operands.
301   /// A tied use operand cannot have a register class, use the register class
302   /// from the def operand instead.
getFlagWordForRegClass(unsigned InputFlag,unsigned RC)303   static unsigned getFlagWordForRegClass(unsigned InputFlag, unsigned RC) {
304     // Store RC + 1, reserve the value 0 to mean 'no register class'.
305     ++RC;
306     assert(!isImmKind(InputFlag) && "Immediates cannot have a register class");
307     assert(!isMemKind(InputFlag) && "Memory operand cannot have a register class");
308     assert(RC <= 0x7fff && "Too large register class ID");
309     assert((InputFlag & ~0xffff) == 0 && "High bits already contain data");
310     return InputFlag | (RC << 16);
311   }
312 
313   /// Augment an existing flag word returned by getFlagWord with the constraint
314   /// code for a memory constraint.
getFlagWordForMem(unsigned InputFlag,unsigned Constraint)315   static unsigned getFlagWordForMem(unsigned InputFlag, unsigned Constraint) {
316     assert(isMemKind(InputFlag) && "InputFlag is not a memory constraint!");
317     assert(Constraint <= 0x7fff && "Too large a memory constraint ID");
318     assert(Constraint <= Constraints_Max && "Unknown constraint ID");
319     assert((InputFlag & ~0xffff) == 0 && "High bits already contain data");
320     return InputFlag | (Constraint << Constraints_ShiftAmount);
321   }
322 
convertMemFlagWordToMatchingFlagWord(unsigned InputFlag)323   static unsigned convertMemFlagWordToMatchingFlagWord(unsigned InputFlag) {
324     assert(isMemKind(InputFlag));
325     return InputFlag & ~(0x7fff << Constraints_ShiftAmount);
326   }
327 
getKind(unsigned Flags)328   static unsigned getKind(unsigned Flags) {
329     return Flags & 7;
330   }
331 
getMemoryConstraintID(unsigned Flag)332   static unsigned getMemoryConstraintID(unsigned Flag) {
333     assert(isMemKind(Flag));
334     return (Flag >> Constraints_ShiftAmount) & 0x7fff;
335   }
336 
337   /// getNumOperandRegisters - Extract the number of registers field from the
338   /// inline asm operand flag.
getNumOperandRegisters(unsigned Flag)339   static unsigned getNumOperandRegisters(unsigned Flag) {
340     return (Flag & 0xffff) >> 3;
341   }
342 
343   /// isUseOperandTiedToDef - Return true if the flag of the inline asm
344   /// operand indicates it is an use operand that's matched to a def operand.
isUseOperandTiedToDef(unsigned Flag,unsigned & Idx)345   static bool isUseOperandTiedToDef(unsigned Flag, unsigned &Idx) {
346     if ((Flag & Flag_MatchingOperand) == 0)
347       return false;
348     Idx = (Flag & ~Flag_MatchingOperand) >> 16;
349     return true;
350   }
351 
352   /// hasRegClassConstraint - Returns true if the flag contains a register
353   /// class constraint.  Sets RC to the register class ID.
hasRegClassConstraint(unsigned Flag,unsigned & RC)354   static bool hasRegClassConstraint(unsigned Flag, unsigned &RC) {
355     if (Flag & Flag_MatchingOperand)
356       return false;
357     unsigned High = Flag >> 16;
358     // getFlagWordForRegClass() uses 0 to mean no register class, and otherwise
359     // stores RC + 1.
360     if (!High)
361       return false;
362     RC = High - 1;
363     return true;
364   }
365 
getExtraInfoNames(unsigned ExtraInfo)366   static std::vector<StringRef> getExtraInfoNames(unsigned ExtraInfo) {
367     std::vector<StringRef> Result;
368     if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
369       Result.push_back("sideeffect");
370     if (ExtraInfo & InlineAsm::Extra_MayLoad)
371       Result.push_back("mayload");
372     if (ExtraInfo & InlineAsm::Extra_MayStore)
373       Result.push_back("maystore");
374     if (ExtraInfo & InlineAsm::Extra_IsConvergent)
375       Result.push_back("isconvergent");
376     if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
377       Result.push_back("alignstack");
378 
379     AsmDialect Dialect =
380         InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect));
381 
382     if (Dialect == InlineAsm::AD_ATT)
383       Result.push_back("attdialect");
384     if (Dialect == InlineAsm::AD_Intel)
385       Result.push_back("inteldialect");
386 
387     return Result;
388   }
389 
getKindName(unsigned Kind)390   static StringRef getKindName(unsigned Kind) {
391     switch (Kind) {
392     case InlineAsm::Kind_RegUse:
393       return "reguse";
394     case InlineAsm::Kind_RegDef:
395       return "regdef";
396     case InlineAsm::Kind_RegDefEarlyClobber:
397       return "regdef-ec";
398     case InlineAsm::Kind_Clobber:
399       return "clobber";
400     case InlineAsm::Kind_Imm:
401       return "imm";
402     case InlineAsm::Kind_Mem:
403       return "mem";
404     default:
405       llvm_unreachable("Unknown operand kind");
406     }
407   }
408 
getMemConstraintName(unsigned Constraint)409   static StringRef getMemConstraintName(unsigned Constraint) {
410     switch (Constraint) {
411     case InlineAsm::Constraint_es:
412       return "es";
413     case InlineAsm::Constraint_i:
414       return "i";
415     case InlineAsm::Constraint_m:
416       return "m";
417     case InlineAsm::Constraint_o:
418       return "o";
419     case InlineAsm::Constraint_v:
420       return "v";
421     case InlineAsm::Constraint_Q:
422       return "Q";
423     case InlineAsm::Constraint_R:
424       return "R";
425     case InlineAsm::Constraint_S:
426       return "S";
427     case InlineAsm::Constraint_T:
428       return "T";
429     case InlineAsm::Constraint_Um:
430       return "Um";
431     case InlineAsm::Constraint_Un:
432       return "Un";
433     case InlineAsm::Constraint_Uq:
434       return "Uq";
435     case InlineAsm::Constraint_Us:
436       return "Us";
437     case InlineAsm::Constraint_Ut:
438       return "Ut";
439     case InlineAsm::Constraint_Uv:
440       return "Uv";
441     case InlineAsm::Constraint_Uy:
442       return "Uy";
443     case InlineAsm::Constraint_X:
444       return "X";
445     case InlineAsm::Constraint_Z:
446       return "Z";
447     case InlineAsm::Constraint_ZC:
448       return "ZC";
449     case InlineAsm::Constraint_Zy:
450       return "Zy";
451     default:
452       llvm_unreachable("Unknown memory constraint");
453     }
454   }
455 };
456 
457 } // end namespace llvm
458 
459 #endif // LLVM_IR_INLINEASM_H
460