9 ms·
Inverting a binary tree using x64 assembly
- scotty79 4y agoWait, so this whole mystical inverting is just swapping left and right children of all nodes?
- raxxorraxor 4y agox32 converter for GNU/Linux: sed -i 's/r//g' invert_tree.asm > invet_tee.asm
- account42 4y agox32 is still amd64. Perhaps you meant x86 but see the other comments for that.
- teknas 4y agoIt's not that easy, you also have to account for the pointer sizes (4 bytes instead of 8). Also alignment requirements are different on x32.
- _8j50 4y agoIt's not only that either. OP used rdi because of calling convention, in x32 you would need to arguments on the stack instead and reference them +ebp instead of using registers if you want non-asm code to call your function.
- junon 4y agox16, you mean :D
- fear91 4y agoYou can use the 32bit xor to reset the register. Also TEST REG,REG might be better for checking if it’s zero.
- _8j50 4y agoIs 32 bit cheaper? Still 1 cycle.
- nixpulvis 4y agoI was thinking of this from the perspective of CPU pipeline pressure, but in reality it seems prosessors are indeed smart enough to avoid burdoning the ALUs execution with these kinds of special cases. Read more here https://stackoverflow.com/questions/17981447/microarchitectural-zeroing-of-a-register-via-the-register-renamer-performance-v/18027854#18027854 https://stackoverflow.com/questions/17981447/microarchitectu... > [...] these zeroing instructions extremely efficient, with a throughput of four zeroing instructons per clock cycle. Also, the xor instruction takes up the smallest amount of .text space (right?).
- scheme271 4y agoThe xor reg, reg is also special cased because it's a quick way for compilers to reinitialize a register and indicate that future uses of that register don't depend on any previous operations. It helps the cpu to parallelize any future instructions that use that register since the cpu knows that those instructions don't depend on anything that happens before the the xor.
- Someone 4y agoIt’s not special cased because it's a quick way for compilers to reinitialize a register and indicate that future uses of that register don't depend on any previous operations, it’s special cased to give compilers a quick way to reinitialize a register and indicate that future uses of that register don't depend on any previous operations. https://randomascii.wordpress.com/2012/12/29/the-surprising-subtleties-of-zeroing-a-register/ https://randomascii.wordpress.com/2012/12/29/the-surprising-... is almost ten years old and thus likely dated, but still may be educational.
- nixpulvis 4y ago
- love2read 4y agoI love seeing people solve leetcode challenges in asm, are there any more blogposts like this?
- chrisseaton 4y agoThe hard bit of solving them is usually the algorithm though - when you know that you can code it in anything.
- kjeetgill 4y agoI'm not well versed in assembly, so learning assembly first would be the hard part! I'm with GP, it's fun seeing how solutions differ between languages as a way to peek into other language communities I don't spend as much time in.
- ummonk 4y agoThis doesn't actually invert a Merkle tree though, since you have to recompute the hashes (except the leaf hashes) when you invert a Merkle tree. Gonna be a no-hire evaluation from me dawg.
- hinkley 4y agoThe tweet this is based on is a joke. To invert a Merkle tree would mean to invert cause and effect. I’m pretty sure the tweet author is implying they want you to find a hash key collision for each node. Hope you have a couple spare universes in your pockets because this is gonna take a while.
- cgh 4y ago> I will be using x64 assembly with the AT&T syntax as it is objectively superior than the Intel syntax. This made me laugh because it must be a reference to this: https://news.ycombinator.com/item?id=33652023 https://news.ycombinator.com/item?id=33652023 > I contend that the AT&T syntax is harmful and bad, and should never be used, for any reason, under any circumstances, by anyone.
- _8j50 4y agoAT&T really is annoying but it feels like the big vs little endian debate. Fairly easy to convert between the two as well.
- sedatk 4y agoFor those who don't know, that's why big and little endian were called that, because the debate was so frivolous. It's a reference to the book Gulliver's Travels by Jonathan Swift in which an island folk was split about from which end you should crack a boiled egg. (I'm a big endian for example).
- classified 4y agoI'm firmly in the little-endian camp for eggs, but big-endian for CPUs.
- sedatk 4y agoFound my archnemesis.
- nurettin 4y agoDo you even care about CPUs anymore?
- classified 4y agoWell, boiled eggs definitely taste better.
- danbruc 4y agoAssume RAX points to the root node and nodes just contain two child pointers and everything is aligned and whatever. :invert cmp rax, 0 jnz swap: ret :swap push rax mov rax, [rax] call invert mov rbx,[rsp] xchg rax, [rbx+8] mov [rbx], rax call invert pop rax ret The last time I used an assembler was before x86-64 was invented, I am not even sure I ever used one in protected mode. But that seems a totally reasonable whiteboard interview question. Written in notepad, might not assemble. Might even be totally incorrect and I am posting it so that the internet generates the warning and error messages. EDIT: After reading the article now, that seems rather inefficient to me, to use local variables on the stack for everything. And why is the function returning a node if it is mutating the tree in place?
- pyinstallwoes 4y agoDid you write Forth at all?
- danbruc 4y agoNo. Why do you ask? EDIT: As Wikipedia describes it as a stack-oriented language, because of my comment about putting everything onto the stack?
- adrian_b 4y agoThe variables on the stack are the most efficient after registers, so you are right that a local variable should be kept into a register if possible, otherwise in the stack, and only then in other places (e.g. if it is too large for the stack). However, when writing in assembly one must pay attention that at least RBX, RBP and R12 through R15 must be preserved by any function (on Windows also RDI and RSI must be preserved). So in your code you should not use RBX, but a volatile register, e.g. RDX or RCX. If you would insist on using RBX, it would have to be saved and restored.
- danbruc 4y agoI know none of the calling conventions in any detail anymore and just used the registers in alphabetical order. Totally expected that this would violate something.
- bugfix-66 4y agoBeing able to read and understand x86-64 assembly (or PTX/SASS for an Nvidia GPU) is much more important than being able to write it. In practice, even when you're writing assembly, you're looking at reference assembly generated by a compiler from C code you wrote. Similarly, the reality is that as a professional programmer you spend no time doing work like leetcode. Instead, you spend a lot of time understanding and slightly modifying (fixing or enhancing/extending) code. With the rise of language model code completion systems (e.g., Microsoft Copilot) even more time will be spent inspecting and understanding code to find problems. With these facts in mind, I have been building a new form of leetcode: https://BUGFIX-66.com https://BUGFIX-66.com Most puzzles are interesting algorithms that you will learn useful techniques from, so it's never a waste of time to think about them. And even though the bugs are all quite trivial, I can see it's very challenging for many people. It's about half-way ready to launch, needing 30 more puzzles. I am working my way through Knuth's The Art of Programming Volume 4B and today I'll see if Algorithm X (Dancing Links Exact Cover Backtracking) can be made to fit for Bugs 38 and 39 (or whether it's too complicated).
- TheRealPomax 4y agoThis is pretty damn cool, but unfortunately you failed the interview as you accepted the challenge to use x86 assembler, but solved the problem using a different programming language from the one we asked you to use. We'll keep your resume on file, and if there are any openings in the future we encourage you to apply for those.
- teknas 4y ago(I am the post author). I wrote the original version of this post using x86, but leetcode won't accept it. So I had to improvise...
- penguin_booze 4y agoThe feedback we received indicates that you used the backspace key twice during coding. We expect higher precision than that. Also, we'd like to remind you that you can only re-apply after our cool-off period, which is 25 years.
- wheelerof4te 4y agoOooh. So that's why people invented C.
- deleted 4y ago[deleted]
- devit 4y agoThat solution is terrible, with a bad algorithm that requires O(tree_height) space (the optimal one involves temporarily using left/right pointers as a parent pointer so that you only need constant space) and lacking any sort of assembly optimization, being worse than what a compiler would produce (e.g. it's a real mystery how the author managed to decide that local_right should be spilled on the stack). Definitely not what you want to submit to someone testing your programming skills.
- deleted 4y ago[deleted]
- Kranar 4y agoYou're alluding to using the Morris traversal algorithm which can traverse a binary tree in O(1) space, but Morris traversal is actually much much slower than using a stack, especially as is used by this algorithm. Doing a Morris traversal requires at a minimum twice the number of operations as using a stack, and due to its cache unfriendly nature will in practice be closer to 4x slower. You typically only use Morris traversal on exceptionally large trees, and by large I mean when working with data that lives on a disk. It's definitely the exception, not the norm.
- aftbit 4y agoWhat does it mean to "invert" a binary tree?
- tom_ 4y ago"Flip" or "mirror" is probably a better term. It seems the goal is to swap left and right: https://leetcode.com/problems/invert-binary-tree/ https://leetcode.com/problems/invert-binary-tree/
- LanceH 4y agoI don't get why this one is the meme. Just because it's recursion? Because it's (nearly) pointless? There are so many other algorithms I find more difficult/more tedious.
- plasticchris 4y agoI think it’s a meme because the home brew author tweeted that he was rejected by Google for failing to invert a binary tree.
- kristov 4y agoIs there a practical reason to do this in a real-world program?
- dekhn 4y ago
- pixel_tracing 4y agoSo anyone have good recommendations on learning assembly? I followed the link to the instructions ABI but can’t really read on my device.
- trelane 4y agoFor learning assembly, usually you learn the syntax for your assembler. The rest of it (the majority of it) is then learning what instructions are available on your platform. I liked http://rayseyfarth.com/asm/ http://rayseyfarth.com/asm/ as an intro to both. I'd already had a class on computer architecture that did assembly before that, though. Once you get going with that, you can download and read the Intel or AMD programmers manuals. Of course, this assumes x86_64.